PHP - Replace new lines with single space in string

Discuss coding issues, and scripts related to PHP and MySQL.
PloMar
Posts:48

PHP - Replace new lines with single space in string

Hello
How can I replace the new lines with a single space in a string in PHP?
For example I have this $str variable with a string content with multiple lines:

Code: Select all

$str = 'First line
Second row
Other line ...'; 
And I want to result this $str string:

Code: Select all

$str = 'First line Second row Other line ...'; 

Admin Posts:805
You can use str_replace() with PHP_EOL.
Example:

Code: Select all

$str = 'First line
Second row
Other line ...';
$str = str_replace(PHP_EOL, ' ', $str);
echo $str; 
Or preg_replace() with RegExp.
Example (will replace also multiple white spaces with single space):

Code: Select all

$str = 'First line
Second row      
Other line ...';
$str = preg_replace('/\s+/', ' ', trim($str));;
echo $str;