7

我想将换行符转换为段落。

例如

$string = "1st paragraph

2nd paragraph


3rd paragraph 
";

我想得到,

<p>1st paragraph</p>
<p>2nd paragraph</p>
<p>3rd paragraph</p>

和,

$string = "1st paragraph

2nd paragraph
a line break

3rd paragraph 
";

进入,

<p>1st paragraph</p>
<p>2nd paragraph<br/>a line break</p>
<p>3rd paragraph</p>

regex和有可能reg_replace吗?或者其他更好的东西 - xpath

这个我试过了,还没有结果

echo preg_replace("'/^(.*?)(<br\s*\/?>\s*)+/'", "<p>$1</p>", nl2br($string));
4

2 回答 2

16

你可以反过来做:首先用段落替换多个换行符,然后用<br>元素替换单个换行符。

$str = preg_replace('/\n(\s*\n)+/', '</p><p>', $str);
$str = preg_replace('/\n/', '<br>', $str);
$str = '<p>'.$str.'</p>';

您还应该首先规范化行尾(windows 风格到 unix 风格):

function normalize($str) {
    // Normalize line endings
    // Convert all line-endings to UNIX format
    $s = str_replace("\r\n", "\n", $str);
    $s = str_replace("\r", "\n", $s);
    // Don't allow out-of-control blank lines
    $s = preg_replace("/\n{2,}/", "\n\n", $s);
    return $s;
}
于 2013-02-07T22:48:09.917 回答
4

另一个解决方案:

$string = preg_replace('/\n{2,}/', "</p><p>", trim($string));
$string = preg_replace('/\n/', '<br>',$string);
$string = "<p>{$string}</p>";
于 2013-02-07T22:55:53.843 回答