我有
<pre>
Line one
Line two
Line three
Line four
Line five
Line six
</pre>
如果我删除预标记,它就会变为
第一行 第二行 第三行 第四行 第五行 第六行
使用br替换新行的正则表达式是什么,以便在剥离预标记后每行都是单独的。
答案 0 :(得分:1)
在每个位置,您需要检查您是否在有效的<pre>
标记内:
~(?s)(?<!<pre>)\R(?!</pre>)(?=((?!<pre>).)*</pre>)~
说明:
(?s) # Set DOT_ALL modifier
(?<!<pre>) # Assert if we are not immediately after an opening <pre> tag
\R # We need new-lines only
(?!</pre>) # Not followed by a closing </pre> tag
(?= # Beginning of a positive lookahead
((?!<pre>).)* # To look if we are not behind an opening <pre> tag (inside a <pre> tag)
</pre> # Which has a closing </pre> tag
) # End of lookahead
注意 :如果您嵌套了<pre>
代码(!)
但如果您愿意使用DOM
,那么有一个更合适的解决方案:
<?php
$html = <<< HTML
<div>
<div>
test
test
test
</div>
<pre>
Line one
Line two
Line three
Line four
Line five
Line six
</pre>
</div>
HTML;
$dom = new DOMDocument;
@$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$preTags = $dom->getElementsByTagName('pre');
foreach ($preTags as $key => $pre) {
$pre->nodeValue = str_replace(PHP_EOL, '~*~*', $pre->nodeValue);
}
echo str_replace("~*~*", '<br />', $dom->saveHTML());
输出:
<div>
<div>
test
test
test
</div>
<pre><br />Line one<br />Line two<br />Line three<br />Line four<br />Line five<br />Line six<br /></pre>
</div>