preg_replace:将换行符转换为段落

时间:2013-02-07 22:44:24

标签: php regex

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

例如

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

是否可以使用regexreg_replace?还是其他更好的东西 - xpath

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

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

2 个答案:

答案 0 :(得分:15)

你可以反过来做:首先用段落替换多个换行符,然后用<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;
}

答案 1 :(得分:4)

又一个解决方案:

$string = preg_replace('/\n{2,}/', "</p><p>", trim($string));
$string = preg_replace('/\n/', '<br>',$string);
$string = "<p>{$string}</p>";