简体   繁体   English

带有“pre”标签和“nl2br”的双换行符

[英]Double line breaks with 'pre' tag and 'nl2br'

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.我使用nl2br函数作为pre标签,但我遇到了一个奇怪的问题:有 2 个换行符但只有一个<br />标签。

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

Wrapping text in a <pre> tag will force it to be displayed as written: including spaces, tabs and new lines.将文本包裹在<pre>标签中将强制它以书面形式显示:包括空格、制表符和换行符。 Therefore the carriage return will create a new line AND the <br /> will create a second new line.因此,回车将创建一个新行, <br />将创建第二个新行。

preg_replace ("/\\n+/", "", $pre)或者更好的preg_replace ("/[\\n\\r]+/", "", $pre)

当您在 pre 块中编写它时,您不需要应用 nl2br() 。

I had the same problem.我有同样的问题。 The correct answer is much simpler.正确答案要简单得多。 Don't use nl2br with pre.不要将 nl2br 与 pre 一起使用。

nl2br adds <br /> to text for html, but the pre tag already preserves the text format. nl2br 将<br />添加到 html 的文本中,但是 pre 标签已经保留了文本格式。 That's what it means.这就是它的意思。 <pre> = preformatted. <pre> = 预格式化。

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>完成它的工作。

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

Or better still:或者更好:

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

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

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