Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple new lines only

I am trying to do something kind of unusual. I want to replace multiple new lines with two new lines. There are plenty of questions like that but not exactly, see:

Hello\n\n\nWorld\n\n\n\n!

Should become

Hello\n\nWorld\n\n!

This however

Hello\nWorld\n!

Should stay the same. The problem with my regex is that it replaces single new lines with two.

preg_replace('"(\r?\n)+"', "\n\n", $somevar)

like image 733
php_nub_qq Avatar asked May 14 '26 19:05

php_nub_qq


1 Answers

something like this?

preg_replace('"(\r?\n){2,}"', "\n\n", $somevar)
like image 171
jambriz Avatar answered May 17 '26 08:05

jambriz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!