how to remove new lines and returns from php string? how to remove new lines and returns from php string? php php

how to remove new lines and returns from php string?


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


You have to wrap \n or \r in "", not ''. When using single quotes escape sequences will not be interpreted (except \' and \\).

The manual states:

If the string is enclosed in double-quotes ("), PHP will interpretmore escape sequences for special characters:

  • \n linefeed (LF or 0x0A (10) in ASCII)

  • \r carriage return (CR or 0x0D (13) in ASCII)\

  • (...)


Something a bit more functional (easy to use anywhere):

function replace_carriage_return($replace, $string){    return str_replace(array("\n\r", "\n", "\r"), $replace, $string);}

Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.