Best preg-replace questions in March 2011

Replace newlines, but keep the blank lines

5 votes

I want to replace newlines (\r\n) with space, but I want to keep the blank lines. In other words, I want to replace \r\n with ' ', if \r\n is not preceded by another \r\n. For example:

line 1

line 2
line 3
line 4

Shold end up as...

line 1

line 2 line 3 line 4

But not as "line 1 line 2 line 3 line 4", which is what I'm doing right now with this

preg_replace("/\r\n/", " ", $string);

Try this:

(?<!\n)\n(?!\n)

Of course, you can change \n to whatever you need.

Working example: http://ideone.com/dF5L9