简体   繁体   中英

New line string “\n” not being recorgnized by nl2br

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

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

nl2br — Inserts HTML line breaks before all newlines in a string

It doesn't replace newlines with line breaks, it inserts it before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM