0

When I assign a variable (or even a string literal) containing several cr lf character pairs to an empty div or p element using a php echo statement the cr lf are gone replaced by a single space char (0x20) and so the new line formatting is lost. The text is displayed as one long line although the element does wrap it.

It seemed that the cr lf was gone by looking at the displayed text. I verified this by copy-pasting the displayed text into a hex editor. How do I tell php to retain the cr lf characters in the text file? Here's the assignment code:

echo "<div class='showBox'><p> $content </p></div>";

This has the same results with or without the enclosing p element.

Banjobum
  • 57
  • 8
  • See [PHP New Line](http://stackoverflow.com/questions/3206531/php-new-line-break-in-emails) – eyoung100 Aug 20 '14 at 20:46
  • This is not a php problem, it is how HTML is rendered in the browser. It is also what the `
    ` is generally used for.
    – hcoat Aug 20 '14 at 20:46
  • Just checked again and see that cr lf pair was not replaced by the cr lf. It was there already in the text as expected. But the cr lf was still missing of course. – Banjobum Aug 20 '14 at 20:47
  • @hcoat Granted, but, "How do I tell php to retain the cr lf characters in the text file?" If he inserts a NewLine in $content, he wont need to worry how the HTML is Rendered – eyoung100 Aug 20 '14 at 20:49
  • Yes. Enclosing the $content in
     tags does the trick. I was never quite sure what those were for. Now I know. Thanks.
    – Banjobum Aug 20 '14 at 20:50
  • @hcoat The $content variable has the cr and lf characters in it. As E Carter Young said, it's how it is rendered by html. I suspect they want to be able to dynamically wrap content if the user resizes the enclosing elements. That's a feature I want to retain. I also don't want the constant width characters that
     imposes. I can see I will have to process the text to get the effect I'm after. I was hoping to avoid that. Thanks for your input.
    – Banjobum Aug 20 '14 at 21:47
  • @Banjobum you could consider using css to wrap content in a `
    ` tag. [wrap pre tag content](http://stackoverflow.com/questions/248011/how-do-i-wrap-text-in-a-pre-tag)
    – hcoat Aug 20 '14 at 22:28

1 Answers1

0

After trying many schemes by chance I discovered a built in php function that produces the exact output format I was hoping for. By executing . .

$content = nl2br($content);

. . before echoing the html to the browser . .

echo "<div class='showBox'><p class='dispContent'>$content></p></div>";

. . the displayed output now retains the blank lines the user entered with the (ENTER) key.

Thanks to both commenters for the valuable hints which led me to this useful discovery.

Banjobum
  • 57
  • 8