用 Regex 替换 PHP 中的双 br 段落

Replace double br with paragraphs in PHP with Regex

我有以下文本(来自 SQL 的字符串):

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

此行由以下人员处理:

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;
}

这应该return:

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

但是 returns

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

如何修复 </p><p></p><p> 部分,那里应该只有 </p><p>

这将多个连续的段落标签合并为一个:

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

Demo

这将删除所有空段落:

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