简体   繁体   English

如何使用nl2br删除\\ n并添加换行符

[英]How to use nl2br to remove \n and add breaks

I'm having some trouble getting nl2br to do what I want. 我在让nl2br做我想做的事情时遇到了麻烦。

Can someone explain why nl2br doesn't change the \\n in the JSON data to < br /> in my PHP? 有人可以解释为什么nl2br不改变\\n在JSON数据< br />在我的PHP?

Here is the code: 这是代码:

$page = file_get_contents('JSON_FEED_URL');
$page2 = nl2br($page);

When I echo $page2 and view the HTML page it comes out as a big wall of text. 当我回显$page2并查看HTML页面时,它就像是一堵大墙。

Try 尝试

$page = file_get_contents('JSON_FEED_URL');
$page2 = preg_replace("/\\n/m", "<br />", $page);  

As said, str_replace would also work a tad faster, but the above counts of multiline breaks. 如前所述, str_replace也可以更快地工作,但是上面的多行中断计数。

nl2br does not replace the new lines, only ads the <br> tags. nl2br不会替换新行,仅广告<br>标签。 In HTML there is no need to remove the new line characters as they are considered to be white space which is collapsed to a single space for display. 在HTML中,不需要删除换行符,因为它们被认为是空格,它被折叠为一个空格以供显示。 This fact is the very reason for having the <br> tag. 这是拥有<br>标签的真正原因。

Since you say that you can see the \\n s when echoing (instead of a newline in the source), this probably means that your \\n s are literal, and not "proper" newlines. 因为您说在回显时可以看到\\n (而不是源中的换行符),所以这很可能意味着您的\\n是文字,而不是“适当的”换行符。 This is because your JSON is read as a string. 这是因为您的JSON是作为字符串读取的。 Fix this by calling json_decode(); 通过调用json_decode();解决此问题json_decode();

$page2 = nl2br(json_decode($page));

Explanation: 说明:
The string 字符串

line1
line2

is in JSON saved as 在JSON中另存为

"line1\nline2"

but that \\n is not a real newline, just normal characters. 但是\\n不是真正的换行符,只是普通字符。 By decoding the JSON, it will be correct. 通过解码JSON,它将是正确的。

nl2br did not interpret \\n to <br /> in HTML because they were literal slashes followed by n. nl2br不会在HTML nl2br \\n解释为<br /> ,因为它们是nl2br斜杠,后跟n。

On your source, the text looks like the following: 在您的来源上,文本如下所示:

 FRIDAY THROUGH WEDNESDAY.\n\nMORE RAIN IS

Should be something similar to the ff so that it'll be interpreted: 应该与ff类似,以便对其进行解释:

 FRIDAY THROUGH WEDNESDAY.

 MORE RAIN IS

You can address your problem by using str_replace() or if you can update your code when putting content on "JSON_FEED_URL", add nl2br before putting those content. 您可以使用str_replace()解决问题,或者如果将内容放在“ JSON_FEED_URL”上时可以更新代码, nl2br在放置这些内容之前添加nl2br

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

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