Search code examples
phpregexnl2br

Replace double br with paragraphs in PHP with Regex


I have the following text (string from SQL):

Paragraph \n Newline \n\n Paragraph2 \n\n\n\n Paragraph3

This line is processed by:

function nl2brAndParagraphs($text) {
    $br = nl2br($text);
    $data = preg_replace('/^\s*(?:<br\s*\/?>\s*)*/i', '', $br); //Remove any whitespace and br- tags that are at the beginning of the text
$data = preg_replace('/\s*(?:<br\s*\/?>\s*)*$/i', '', $data); //Remove any whitespace and br- tags that are at the end of the text

$data = preg_replace('#(?:<br\s*/?>\s*?){2,}#','</p>
    <p>',$data); //Replace multiple line breaks with paragraphs
$data = '<p>'.$data.'</p>';
return $data;
}

This should return:

<p>Paragraph <br /> Newline </p><p> Paragraph2 </p><p> Paragraph3</p>

but returns

<p>paragraph1 <br /> Newline </p><p> paragraph2 </p><p></p><p> paragraph3</p>

How do I fix the </p><p></p><p> part, where there only should be </p><p>?


Solution

  • This removes any empty paragraphs:

    $data = preg_replace('/<p[^>]*>\s*?<\/p[^>]*>/', '', $data);