PHP Question

Regex to remove certain number of \n at the end of string

How to remove maximum number of

\n
at the end of string using regex?

The
\n
removal is as expected when search position at start of the string
^
, but i can't have a correct result when search position at end of the string.

$subject = "\n\n\nsubject\n\n\n";
# maximum removal
$count = 2;

# expect maximum 2 LF removed, 2 removed
var_dump(preg_replace("#^\\n{0,$count}#",null,$subject));

# expect maximum 2 LF removed, 3 removed
var_dump(preg_replace("#\\n{0,$count}\$#",null,$subject));


however when using \r both script result as expected

Answer

A regex to remove some specific number of newlines at the end of string, you need to use \z anchor that matches at the very end of the string:

$subject = "\n\n\nsubject\n\n\n";
$count = 2;
echo preg_replace("#\n{1,$count}\\z#",null,$subject);

See the IDEONE demo

The $ anchor may match at the final newline in the string, thus, you cannot use it. Also, there is no point matching 0 newlines to remove them, thus, 1 should be the lower bound for the limiting quantifier.

However, you may make $ match at the very end of the string by using /D modifier (see PCRE_DOLLAR_ENDONLY modifier):

preg_replace("#\n{1,$count}$#D",null,$subject)
                           ^^^

Here is some relevant excerpt from the PHP PCRE documentation:

A dollar character ($) is an assertion which is TRUE only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). ... The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching time.