开发者

How to preserve line breaks in the database on user submitted text?

开发者 https://www.devze.com 2022-12-24 13:09 出处:网络
Users enter text through a text area element, much like we enter questions on StackOverflow. What\'s the best way to preserve the l开发者_开发问答ine spacing in the database so that it can be reprodu

Users enter text through a text area element, much like we enter questions on StackOverflow.

What's the best way to preserve the l开发者_开发问答ine spacing in the database so that it can be reproduced on the front end? The idea is the text should appear with the same line breaks and blank lines as entered originally by the user.


Well, HTTP POST data comes in (almost) just as the user typed it in the textarea; if your database stores what was typed verbatim, it isn't going to be a problem, really. I think what you are thinking of is how to display the information back so that it formats properly in a web browser.

For that, you'll have to modify the text when it comes out of the database, For instance, in PHP:

$formatted_text = preg_replace(
    # patterns
    array('/\\r?\\n/', '/ /'),

    # replacements
    array('<br />', '&nbsp;'),

    # input text
    $text_from_database
);

will preserve both line breaks and multiple spaces.

0

精彩评论

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