PHP-REGEX - 在前置标签中用 <br> 替换换行符
PHP-REGEX - Replace line break with <br> within pre tags
我有
<pre>
Line one
Line two
Line three
Line four
Line five
Line six
</pre>
如果我去掉前置标签,它会变成
第一行
二号线
三号线
四号线
五号线
第六行
用 br 替换新行的正则表达式是什么,以便在剥离 pre 标记后每行都是分开的。
在每个位置你都需要检查你是否在有效的 <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>
标签 (!)[=18,它不会提供预期的结果=]
但是如果您愿意使用 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>
我有
<pre>
Line one
Line two
Line three
Line four
Line five
Line six
</pre>
如果我去掉前置标签,它会变成
第一行 二号线 三号线 四号线 五号线 第六行
用 br 替换新行的正则表达式是什么,以便在剥离 pre 标记后每行都是分开的。
在每个位置你都需要检查你是否在有效的 <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>
标签 (!)[=18,它不会提供预期的结果=]
但是如果您愿意使用 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>