My Books

Text Processing with JavaScript

Solve complex text validation, extraction, and modification problems efficiently in JavaScript.

Modern Async JavaScript

Delve into async features of JavaScript from ES2020 through ESNext. Start building custom asynchronous iterators and generators, and more for fast, lean code.

JavaScript Brain Teasers

Ready to test your JavaScript skills? Challenge yourself with these brain-teasing puzzles, supercharge your learning journey, and emerge as a JavaScript pro.

A Better Alternative to PHP nl2br

This article explores different options for preserving paragraph formatting in PHP. It will show you how to display entered text in a textarea properly without the need to use the PHP nl2br function.

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

Have your say