Double line breaks with 'pre' tag and 'nl2br'

心不动则不痛 提交于 2019-12-24 03:19:16

问题


I used nl2br function for pre tags, but I've encountered a strange problem: there are 2 line breaks but there's only one <br /> tag.

For example:

code in line 1<br />
code in line 2<br />

Displays as:

code in line 1

code in line 2

instead of:

code in line 1
code in line 2

回答1:


Wrapping text in a <pre> tag will force it to be displayed as written: including spaces, tabs and new lines. Therefore the carriage return will create a new line AND the <br /> will create a second new line.




回答2:


preg_replace ("/\n+/", "", $pre) or even better preg_replace ("/[\n\r]+/", "", $pre)




回答3:


You don't need to apply nl2br() when you're writing it inside a pre block.




回答4:


I had the same problem. The correct answer is much simpler. Don't use nl2br with pre.

nl2br adds <br /> to text for html, but the pre tag already preserves the text format. That's what it means. <pre> = preformatted.

Yes, something like this will work, until it doesn't.

<pre>
    preg_replace ("/[\n\r]+/", "",nl2br(file_get_contents("/crashbody.txt")))
</pre>

But that's silly. You're adding line breaks and removing them. To preserve your whitespace and your line breaks, let <pre> do it's job.

<pre>
    file_get_contents("/crashbody.txt")
</pre>

Or better still:

<div style = "white-space: pre; text-align:left;">
    file_get_contents("/crashbody.txt")
</div>


来源:https://stackoverflow.com/questions/11275006/double-line-breaks-with-pre-tag-and-nl2br

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!