从字符串中删除除特定正则表达式之外的所有标签

Remove all tags from string except a certain regex

我写了 this regex :

<span class="icon(.*?)><\/span>

我得到了这个字符串:

<p style="text-align: center;"><span style="font-size: 1em;">Text 1 <span style="font-weight: bold;">TEXT 2</span><span style="color: #e67e23; font-size: 1.2em;"><span class="icon x-small icon-play"></span>&nbsp;</span><span style="color: #e03e2d;">Text 3</span> <span style="color: #a68965;">Text 4 </span></span><span style="font-size: 0.7em; color: #000000;">Text 5</span></p>

我想从该字符串中删除所有标签,但上面的正则表达式产生的标签除外。所以我会得到这个最终结果:

Text 1 Text 2<span class="icon x-small icon-play"></span>&nbsp;Text 3 Text 4 Text 5

如您在此输出中所见,除我要查找的标签外,所有标签均已清除。

我查看了 PHP 的 strip_tags but unfortunately they do not take a regex as a second parameter, thus not doing what I'm looking for. I tried doing it with a preg_replace,但我无法创建如此复杂的正则表达式。

知道使用正则表达式还是不使用正则表达式的最佳方法是什么吗?

使用

preg_replace('/<span class="icon.*?><\/span>(*SKIP)(*F)|<[^<>]+>/', '', $string)

proof

表达式将找到 <span class="icon....></span> 个字符串以使用 (*SKIP)(*F) 忽略它们,然后所有其他标签将被删除(与 <[^<>]+> 匹配)。