用PHP中的段落替换双重br和Regex

时间:2015-08-17 21:00:55

标签: php regex nl2br

我有以下文本(来自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;
}

这应该返回:

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

但返回

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

如何修复</p><p></p><p>部分,其中只有</p><p>

2 个答案:

答案 0 :(得分:0)

这会将多个连续段落标记合并为一个:

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

Demo

答案 1 :(得分:0)

这会删除所有空段落:

MyCollection.CollectionChanged += System.Specialized.NotifiyCollectionChangedEventHandler(myMethod);