Double line breaks with 'pre' tag and 'nl2br'
Asked Answered
O

4

2

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
Opus answered 30/6, 2012 at 14:47 Comment(1)
nl2br will insert <br /> for each \r and for each \n if there's any character at all between them. Show your input string.Edaphic
P
2

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.

Pishogue answered 30/6, 2012 at 14:53 Comment(2)
true, but how we can remove new lines before we send it to browser?Opus
Does this need to be encapsulated in a <pre> tag?Grolier
S
0

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

Salomesalomi answered 30/6, 2012 at 14:54 Comment(7)
@Opus - try preg_replace_all("/<br\b.*?>/", "", $text)Escorial
thanks for reply, but it just remove br not invisible line break, in output there is just one br tag but browser render tow line break!Opus
@Opus - there should be no <br \> tags inside of <pre> ... </pre>Escorial
my means was without preg_replace_all("/<br\b.*?>/", "", $text) there is one br tag and i just need to remove invisible line break, not br, removing br tag case missing line break problem, when user make copy and past, in some browser like chrome safari and...Opus
@Opus - you should consider to update your question, to make it clear, show us more input/output and code you have, otherwise this is just waist of time, sorry........Escorial
ya i think so but i can't explain it more, i think it's a strange problem, maybe i must try more about solution, i must check all things. thanks.Opus
problem solved with your guide, but i replaced \r\n insted of \n\r and invisible lines disappeared! thanks a lot.Opus
N
0

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

Nimwegen answered 30/6, 2012 at 15:45 Comment(0)
R
0

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>
Rhinitis answered 4/1, 2015 at 15:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.