How to replace one or two consecutive line breaks in a string?
Something like
preg_replace('/(\r|\n|\r\n){2,}/', '<br/><br/>', $text);
should work, I think. Though I don't remember PHP syntax exactly, it might need some more escaping :-/
\R
is the system-agnostic escape sequence which will match \n
, \r
and \r\n
.
Because you want to greedily match 1 or 2 consecutive newlines, you will need to use a limiting quantifier {1,2}
.
Code: (Demo)
$string = "Porcupines\nare\n\n\n\nporcupiney.";echo preg_replace('~\R{1,2}~', '<br />', $string);
Output:
Porcupines<br >are<br /><br />porcupiney.
Now, to clarify why/where the other answers are incorrect...
@DavidZ's unexplained answer fails to replace the lone newline character (Demo of failure) because of the incorrect quantifier expression.
It generates:
Porcupines\nare<br/><br/>porcupiney.
The exact same result can be generated by @chaos's code-only answer (Demo of failure). Not only is the regular expression long-winded and incorrectly implementing the quantifier logic, it is also adding the s
pattern modifier.
The s
pattern modifier only has an effect on the regular expression if there is a dot metacharacter in the pattern. Because there is no .
in the pattern, the modifier is useless and is teaching researchers meaningless/incorrect coding practices.