Remove new lines from string and replace with one empty space

James picture James · Sep 21, 2010 · Viewed 483.3k times · Source
$string = "
put returns between paragraphs

for linebreak add 2 spaces at end

";

Want to remove all new lines from string.

I've this regex, it can catch all of them, the problem is I don't know with which function should I use it.

/\r\n|\r|\n/

$string should become:

$string = "put returns between paragraphs for linebreak add 2 spaces at end ";

Answer

jwueller picture jwueller · Sep 21, 2010

You have to be cautious of double line breaks, which would cause double spaces. Use this really efficient regular expression:

$string = trim(preg_replace('/\s\s+/', ' ', $string));

Multiple spaces and newlines are replaced with a single space.

Edit: As others have pointed out, this solution has issues matching single newlines in between words. This is not present in the example, but one can easily see how that situation could occur. An alternative is to do the following:

$string = trim(preg_replace('/\s+/', ' ', $string));