Replace double br with paragraphs in PHP with Regex

890 Views Asked by At

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>?

2

There are 2 best solutions below

0
On BEST ANSWER

This removes any empty paragraphs:

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

This consolidates multiple consecutive paragraph tags into one:

$data = preg_replace('# (\s*<\/p>\s*<p>){2,}#',' <\/p><p>',$data); 

Demo