Page 1 of 1

PHP - Replace new lines with single space in string

Posted: 21 Jan 2015, 14:27
by PloMar
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 ...'; 

PHP - Replace new lines with single space in string

Posted: 21 Jan 2015, 14:43
by Admin
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;