I have a textarea. User inputs text into the textarea, which can contain line breaks for formatting purposes. I save this text to the mySQL database as is without adding HTML br breaks. This looks like “text blah blah.\n\nText2 blah blah.” in the database record.
I display the text on a regular HTML page using echo nl2br($text); and the text is nicely formatted, with two line breaks showing up as a two sentences with a blank line between them.
When I send the same text to a textarea prepopulated for the user to edit their original entry, I use the following code:
<textarea><?php echo $text;?></textarea>
I expect that I would get a textarea filled with text that includes some double line breaks as are stored in the database. I don’t use nl2br in this case, because doing so would just literally show the HTML characters (not actually create line breaks — in other words display to the user the 6 characters of the br). Instead, what I get is stripping of any double new lines, so that two new lines back-to-back are now single new lines. The single new lines don’t get stripped out completely — they just stay single new lines.
So, in short, when I send text with formatting that should include a blank line between lines of text, what I get is only single new lines, breaking the important formatting of the text).
How can I preserve all of the newlines when outputting text from the database to a textarea?
This works for me:
Note the lack of
line3text and the double\n\n. Loading this form in Firefox gives me a blank line between the line2/line4 text, as expected.Check that your text isn’t being mangled elsewhere, and really is in the database as a double-line break.