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
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Vahid
  • 382
  • 1
  • 6
  • 19
  • 2
    `nl2br` will insert `
    ` for each `\r` *and* for each `\n` if there's any character at all between them. Show your input string.
    – Jon Jun 30 '12 at 14:50

4 Answers4

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.

jaypeagi
  • 3,133
  • 18
  • 33
0

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

Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • @Vahid - try `preg_replace_all("/
    /", "", $text)`
    – Ωmega Jun 30 '12 at 15:02
  • 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! – Vahid Jun 30 '12 at 15:06
  • @Vahid - there should be no `
    ` tags inside of `
     ... 
    `
    – Ωmega Jun 30 '12 at 15:13
  • my means was without `preg_replace_all("/
    /", "", $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...
    – Vahid Jun 30 '12 at 15:18
  • 1
    @Vahid - 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........ – Ωmega Jun 30 '12 at 15:21
  • 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. – Vahid Jun 30 '12 at 15:26
  • 2
    problem solved with your guide, but i replaced `\r\n` insted of `\n\r` and invisible lines disappeared! thanks a lot. – Vahid Jun 30 '12 at 19:09
0

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

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
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>