问题描述
我有一个棘手的HTML代码字符串,其中包含几个前置标记,这些前置标记在其中包含代码(例如python),并且还由应删除的HTML标记修饰。
例如:
for k in l:
i=k.split(':')
print('capital: ',i[0],' lower: ',i[1],' number: ',i[2])
我想清除所有HTML标记(这些标记可能是基本标记,br,em,div,a等)。我不需要解析HTML,我知道regex cannot parse html。
Some text.
<pre>
a = 5 <br/>
b = 3
</pre>
More text
<pre>
a2 = "<a href='something'>text</a>"
b = 3
</pre>
final text
我想使用PHP(使用Some text.
<pre>
a = 5
b = 3
</pre>
More text
<pre>
a2 = "text"
b = 3
</pre>
final text
之类的方法)。例如:
preg_replace
此示例代码显然不会,因为:(1)它仅适用于一个pre标签,并且(2)代码$html = "<html><head></head><body><div><pre class=\"some-css-class\">
<p><strong>
some_code = 1
</p></strong>
</pre></div></body>"; // Compacting things here,for brevity
$newHTML = preg_replace("/(.*?)<pre[^<>]*>(.*?)<\/pre>(.*)/Us","$1".strip_tags("$2",'<p><a><strong>')."$3",$html);
echo $newHTML;
显然不起作用,因为它不处理字符串放在正确的位置(它只会返回“ $ 2”,而不是获取文本并正确地对其进行操作)。
关于如何在PHP中完成此操作的任何建议?谢谢。
解决方法
您将需要使用preg_replace_callback
并在回调主体中调用strip_tags
:
preg_replace_callback('~(<pre[^>]*>)([\s\S]*?)(</pre>)~',function ($m) { return $m[1] . strip_tags($m[2],['p','b','strong']) . $m[3]; },$s);
Some text.
<pre>
a = 5
b = 3
</pre>
More text
<pre>
a2 = "text"
b = 3
</pre>
final text
请注意,在strip_tags
上方会剥离除p
,b
和strong
之外的所有标签。
RegEx详细信息:
-
(<pre[^>]*>)
:匹配<pre...>
并捕获到#1组 -
([\s\S]*?)
:匹配0个或多个字符,包括换行符(惰性),将其捕获到$ 2组中。[\s\S]
匹配包括换行符在内的任何字符。 -
(</pre>)
:匹配</pre>
并捕获到第3组