Canada  united states of america usa  linkedinfacebook   Call Us Today: 866.646.6461

Line break to p (paragraph) tag conversion using php

php logoThere's a useful function in PHP called nl2br, which breaks up a paragraph with regular line breaks and replaces them with <br /> HTML breaks. It works great, but sometimes you need to break the paragrpah into actual paragraphs, separated by <p> and </p>. The function below does exactly that - finds line breaks (\n) and encapsulates the text in <p></p> tags:

function nl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
// It is conceivable that people might still want single line-breaks
// without breaking into a new paragraph.
if ($line_breaks == true)
    return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'), trim($string)).'</p>';
else
    return '<p>'.preg_replace(
    array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
    array("</p>\n<p>", "</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'),
    trim($string)).'</p>';
}

Feel free to use the code, there's no need to reference us. ALT is an IT consulting company, which provides end-to-end IT support, from system maintenance to web development. If you are intereseted in learning more about our services, feel free to contact us.

Last updated Apr 7, 2019