ssam
ssam

Reputation: 93

Replace newlines, but keep the blank lines

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);

Upvotes: 6

Views: 435

Answers (3)

seriousdev
seriousdev

Reputation: 7656

This should do the trick:

preg_replace("/(?<!\n)\n(?!\n)/", " ", $string);

Upvotes: 1

Gumbo
Gumbo

Reputation: 655229

Try this:

 preg_replace("/(.)\r\n(?=.|$)/", "$1 ", $string);

Upvotes: 2

Kobi
Kobi

Reputation: 138017

Try this:

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

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

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

Upvotes: 3

Related Questions