替换前标签之间的新线

时间:2010-06-12 10:27:34

标签: php regex

我想转换

<p>Code is following</p>
<pre>
&lt;html&gt;<br>&lt;/html&gt;
</pre>

<p>Code is following</p>
<pre>
&lt;html&gt;
&lt;/html&gt;
</pre>

我不知道如何编写正则表达式来替换PHP中的pre标签。

我尝试了这段代码Replace newlines with BR tags, but only inside PRE tags

但它不适合我。

4 个答案:

答案 0 :(得分:5)

您使用的代码来自哪个答案?

假设这是接受的答案,只需按以下步骤反转preg_replace()行;

$parts[$idx] = preg_replace('#<br\s*/?>#', "\n", $part);

答案 1 :(得分:0)

你不应该使用正则表达式来匹配html标签,因为理论上它是不可能的。

有一些用于html解析的php库,谷歌上的快速搜索显示了这一点。 http://simplehtmldom.sourceforge.net/

尝试在“pre”标记之间获取代码,并在此处使用简单的正则表达式。

答案 2 :(得分:0)

试试这个:

$newtext = preg_replace('@<pre>.*<br[/>]*?>?</pre>@si','\n',$text);

答案 3 :(得分:-1)

if (preg_match("/<pre>.*(<br(|\s*\/)>).*<\/pre>/m", $str)) {
    $str = preg_replace("/(<br(|\s*\/)>)/", "\n", $str);
}

工作原理相同。只有在<br>内找到<br/>

时,才能取代<br /><pre>...</pre>,{{1}}
相关问题