A php variable contains the following string:
<p>text</p>
<p>text2</p>
<ul>
<li>item1</li>
<li>item2</li>
</ul>
I want to remove all the new line characters in this string so the string will look like this:
<p>text</p><p>text2><ul><li>item1</li><li>item2</li></ul>
I've tried the following without success:
str_replace('\n', '', $str);
str_replace('\r', '', $str);
str_replace('\r\n\', '', $str);
Anyone knows how to fix this?
You have to wrap
\n
or\r
in""
, not''
. When using single quotes escape sequences will not be interpreted (except\'
and\\
).The manual states:
You need to place the
\n
in double quotes.Inside single quotes it is treated as 2 characters
'\'
followed by'n'
You need:
A better alternative is to use
PHP_EOL
as:To remove new lines from string, follow the below code
Something a bit more functional (easy to use anywhere):
Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.
Correct output: