开发者

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 coupl开发者_如何学Ce 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.


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))); ?>


You could use a rich text editor (TinyMCE, CKEditor) on the initial form which will allow the user to create markup without needing to know how to write HTML.

You then save the submitted markup into your DB (optionally filtering it for unwanted markup / scripting).

When displaying, don't use htmlspecialchars / htmlentities as you will want the content to be interpreted as HTML.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜