用于替换换行符的正则表达式

Just want to know why my regular expression is giving me 2 br tags instead of 1 when the string contains ?

I'm trying to replace , , and with the following:

$string="testing 
 testing2";
$result=preg_replace("/?
|
?/", "<br />", $string);
echo "$result";

Thanks

The best match for /? | ?/ on " " is the substring consisting of the first character only (the ). This is because the regex engine tries to find a match for /? / before it starts looking for a match for / ?/.* This is always true for | matches: a match for the part of the regex before the | takes precedence over a match for the regex after it.

And so, having found its first match, it continues from where it left off and discovers that the next character also matches the regex. That's 2 matches, each of which is replaced by a "<br />".

Try doing / ?| ?/ instead.

*(More precisely, it looks for matches for /? / anchored at the start of the string before searching for matches for / ?/ anchored at the start; only if these searches fail does it start looking for matches anchored later in the string.)

You need to add the multiline modifier:

/?
|
?/ms

so:

preg_replace("/?
|
?/ms", "<br />", $string);

Why not use the native nl2br function that achieves the same thing

$string="testing 
 testing2";
echo nl2br($string);

Your expression is performing as expected. Take another look:

/?
|
?/

It seems you believe that alternation (|) should favor the longer match, i.e. not , but that's not the case. Alternation matches whatever matches first, with left-to-right precedence.

Therefore upon encountering a , the is matched by ? and replaced with <br />, and the is matched by ? and replaced again.

What you want instead is

/
|
||
/

but I don't think is generally used, so

/
?|/

should be sufficient.