HTML ignores whitespace, including new lines. In order to display paragraphs properly and not in a continuous block (for example when saving text from a texarea or retrieving it from a database) you have the following options:
- Save text with its HTML.
- Change new lines to <br> tags using nl2br().
- Replace new lines with paragraph tags by creating a custom function.
The Simplest way is to use the nl2br() function. However, It’s not semantic to use line breaks instead of paragraph,. In other words, it makes fake paragraphs. Furthermore, nl2br() function inserts a slash before the closing angle bracket for compatibility with XHTML. Although it’s still compatible with HTML5, I’d prefer to use <br> than <br />. It’s a quick and dirty solution, but not ideal.
In order to save text with its HTML you can use an HTML editor like TinyMCE or CK Editor and then store the result. It’s a better option than nl2br(), but still not ideal.
I wasn’t satisfied with any of these options, so I decide to write my own php function to do the conversion. To use this function you need to pass the text retrieved from your database(or any other source) to the convert() function. It reads the text and whenever it encounters a newline character it wraps up the text in paragraph without adding any
tags.
Here is the code:
function convert ($text) { $text = trim($text); return '<p>' . preg_replace('/[\r\n]+/', '</p><p>', $text) . '</p>'; }
Use it like this:
$text = 'paragraph one. paragraph two.'; echo convert($text);
3 comments