简体   繁体   English

nl2br不会重新组织新的行字符串“ \\ n”

[英]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". 我有一个由Web服务返回的字符串,其中包含换行符“ \\ n”。 When I try to output the string with the nl2br function, the string is returned as is, with "\\n" inside the string. 当我尝试使用nl2br函数输出字符串时,该字符串将按原样返回,并且在字符串中包含“ \\ n”。

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: 替换所有换行以标记br的最佳解决方案是:

<?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: 因为每个操作系统的换行符都有不同的ASCII字符:

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 . 它只是\\n两个字节5c6e ,其中5c\\6en But new line is 0a 但是换行是0a

echo (bin2hex("\n")); // 0a

You could replace \\n with <br /> using str_replace . 您可以使用str_replace\\n替换为<br />

$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 某些代码:http: //3v4l.org/N0FjC#v540

nl2br — Inserts HTML line breaks before all newlines in a string nl2br —在字符串的所有换行符之前插入HTML换行符

It doesn't replace newlines with line breaks, it inserts it before. 它不会用换行符代替换行符,而是将其插入到换行符之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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