Remove new lines from string and replace with one empty space Remove new lines from string and replace with one empty space php php

Remove new lines from string and replace with one empty space


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


A few comments on the accepted answer:

The + means "1 or more". I don't think you need to repeat \s. I think you can simply write '/\s+/'.

Also, if you want to remove whitespace first and last in the string, add trim.

With these modifications, the code would be:

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


Just use preg_replace()

$string = preg_replace('~[\r\n]+~', '', $string);

You could get away with str_replace() on this one, although the code doesn't look as clean:

$string = str_replace(array("\n", "\r"), '', $string);

See it live on ideone