A php variable contains the following string:
text
text2
- item1
- item2
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 interpret more 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.
$str = "Hello World!\n\n";
echo chop($str);
output : Hello World!
Correct output:
'{"data":[{"id":"1","reason":"hello\\nworld"},{"id":"2","reason":"it\\nworks"}]}'
function json_entities( $data = null )
{
//stripslashes
return str_replace( '\n',"\\"."\\n",
htmlentities(
utf8_encode( json_encode( $data) ) ,
ENT_QUOTES | ENT_IGNORE, 'UTF-8'
)
);
}
This should be like
str_replace("\n", '', $str); str_replace("\r", '', $str); str_replace("\r\n", '', $str);
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);