Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I maintain user-formatting of text entered in an HTML form and stored in a MYSQL database?

I have a website in which a user enters text into an html form. The nature of the content is such that it is likely the user will want to write multiple paragraphs. As it stands now, the form sends the text via POST to a PHP file which inserts the text into a database. On another page, the text is pulled from the database and displayed. When it is displayed, all user formatting is gone. Multiple spaces and line breaks are deleted. How can I save the formatting of the user? Instructing him to use HTML tags to format is not feasible for a couple of reasons. I have also considered the <pre> tag, but that creates layout-breaking long lines of text and changes the font.

Any help is very much appreciated.

like image 825
Eric Avatar asked Nov 22 '25 03:11

Eric


1 Answers

I'm assuming you're dealing with just a bunch of plain text entered into a textarea, not some fancy HTML editor as the other answerer assumed.

The reason your line breaks are lost is that HTML doesn't treat line breaks as line breaks. Line breaks are treated as just another space. Only <br> is treated as a line break. (Or <br /> in XHTML) If this is what's happening, you can use the nl2br() function to convert all line breaks into <br>.

Multiple spaces are more difficult. HTML doesn't distinguish between one space and many spaces. Spaces, tabs, line breaks, or any combination thereof, it doesn't matter, it's all treated as a single space. One way to prevent this is to wrap the whole thing in a <pre> or <code> block. But this is ugly unless you're trying to display computer code.

Or if you really desparately need those extra spaces, you could replace all spaces with &nbsp; which forces web browsers to display an extra space. (See edit below.)

Edit: Definitive version which preserves both line breaks and multiple spaces, and also prevents XSS:

<?php echo nl2br(str_replace('  ', ' &nbsp;', htmlspecialchars($text))); ?>
like image 101
kijin Avatar answered Nov 23 '25 16:11

kijin