Reputation: 895
I have a string which is returned by a web service and contains the new line characters, "\n". When I try to output the string with the nl2br function, the string is returned as is, with "\n" inside the string.
Could it be possible that the new line character needs to have some special encoding to be identified as such or am I missing something trivial here?
Hex representation of the input string
48617570747374726173736520315c6e416e737072656368706172746e65723a204d6178204d75737465726d616e6e
Upvotes: 0
Views: 387
Reputation: 15464
48617570747374726173736520315c6e416e737072656368706172746e65723a204d6178204d75737465726d616e6e
According to your hex string it seems that your string does not contain newline. It just \n
- two bytes 5c6e
where 5c
is \
and 6e
is n
. But new line is 0a
echo (bin2hex("\n")); // 0a
You could replace \n
with <br />
using str_replace
.
$string = hex2bin('48617570747374726173736520315c6e416e737072656368706172746e65723a204d6178204d75737465726d616e6e');
echo str_replace('\n', "<br/>\n", $string);
// please note, that '\n' and "\n" are different in PHP, '\n' - just two symbols, "\n" - one new line symbol.
Some code: http://3v4l.org/N0FjC#v540
Upvotes: 2
Reputation: 14180
nl2br — Inserts HTML line breaks before all newlines in a string
It doesn't replace newlines with line breaks, it inserts it before.
Upvotes: 0
Reputation: 2515
to replace all linebreaks to br tag the best solution is:
<?php
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
?>
because each OS have different ASCII chars for line-break:
windows = \r\n
unix = \n
mac = \r
Upvotes: 1