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