yens resmann yens resmann - 1 year ago 74
PHP Question

how to remove new lines and returns from php string?

A php variable contains the following string:


I want to remove all the new line characters in this string so the string will look like this:


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?

Answer Source

You need to place the \n in double quotes.
Inside single quotes it is treated as 2 characters '\' followed by 'n'

You need:

$str = str_replace("\n", '', $str);

A better alternative is to use PHP_EOL as:

$str = str_replace(PHP_EOL, '', $str);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download