New line to paragraph in PHP

Here’s an example of how to convert new line (LF – line feed, ‘\n’) or carriage return (CR, ‘\r’) followed by new line (CR+LF, ‘\r\n’) to <br> or <p>. In case of double or more breaks we’ll get a paragraph but in case of one break we’ll have <br>.

$text = 'Lorem ipsum\r\n\r\ndolor sit\r\namet.';
// double or more nl to <p>
$text = preg_replace('/(\r?\n){2,}/', '</p><p>', $text);
// nl to <br>
$text = preg_replace('/(\r?\n)+/', '<br />', $text);
echo '<p>' . $text . '</p>';

output: <p>Lorem ipsum</p><p>dolor sit<br />amet.</p>

Leave a Reply