正则表达式:如何不替换特定html标签中的特定单词?

问题描述 投票:3回答:1

所以我们假设我有这样的文字:

This is a great test! We're testing something awesome. Click here to <a href="whatever">test it!</a>.

我想为“test”这个词添加一些颜色,但是如果它在一个标签中则没有。我试过这样做:

/(?<!href="(.*?)">)test/

但它不起作用。它的工作原理如下:

/(?<!href="whatever">)test/

但当然我有很多链接,所以这不是一个选择。

整个代码将是这样的:

$replacement = preg_replace('/(?<!href="SOLUTION HERE">)test/','<span style="color: #FF0000;">test</span>',$replacement);

预期结果:

This is a great <span style="color: #FF0000;">test</span>! We're <span style="color: #FF0000;">test</span>ing something awesome. Click here to <a href="whatever">test it!</a>.
php html regex preg-replace
1个回答
4
投票

与html字符串交互的快速,不太可靠的方法是使用正则表达式。 DomDocument(或类似)专门用于解析html,更值得信赖。我将发布正则表达式方式,如果我可以管理它,我将添加一个DomDocument方式。

(*SKIP)(*FAIL)允许您匹配/使用和取消对子字符串的限定,然后在管道之后为您实际要替换的子字符串编写模式。

模式:~(?:<[^>]*>.*?</[^>]*>(*SKIP)(*FAIL))|\btest\b~s

替换:<span style="color: #FF0000;">\0</span>

Pattern Demo

代码:(Demo

$string="This is a great test! We're testing something awesome. Click here to <a href=\"whatever\">test it!</a>.";
$pattern='~(?:<[^>]*>.*?</[^>]*>(*SKIP)(*FAIL))|\btest\b~s';
$replace='<span style="color: #FF0000;">\0</span>';
echo preg_replace($pattern,$replace,$string);

输出:

This is a great <span style="color: #FF0000;">test</span>! We're testing something awesome. Click here to <a href="whatever">test it!</a>.
© www.soinside.com 2019 - 2024. All rights reserved.