0

我有以下文本(来自 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>哪里?

4

2 回答 2

0

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

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

演示

于 2015-08-18T03:53:59.707 回答
0

这将删除任何空段落:

$data = preg_replace('/<p[^>]*>\s*?<\/p[^>]*>/', '', $data);
于 2015-08-19T22:45:23.483 回答