Php Regex:如何不替换任何html标记中的特定单词?

Php Regex:如何不替换任何html标记中的特定单词?,php,html,regex,preg-replace,Php,Html,Regex,Preg Replace,假设我有这样一个文本: This is a great test! We're testing something awesome. Click here to <a href="whatever">test it!</a>. /(?<!href="whatever">)test/ $replacement = preg_replace('/(?<!href="SOLUTION HERE">)test/','<span style="co

假设我有这样一个文本:

This is a great test! We're testing something awesome. Click here to <a href="whatever">test it!</a>.
/(?<!href="whatever">)test/
$replacement = preg_replace('/(?<!href="SOLUTION HERE">)test/','<span style="color: #FF0000;">test</span>',$replacement);
这是一个很棒的测试!我们正在测试一些很棒的东西。单击此处查看。
我想给单词“test”添加一些颜色,但如果它在一个标签中,就不需要了。 我试过这样做:

/(?<!href="(.*?)">)test/
/(?)测试/
但它不起作用。 它的工作原理如下:

This is a great test! We're testing something awesome. Click here to <a href="whatever">test it!</a>.
/(?<!href="whatever">)test/
$replacement = preg_replace('/(?<!href="SOLUTION HERE">)test/','<span style="color: #FF0000;">test</span>',$replacement);
/(?)测试/
但是我当然有很多链接,所以这不是一个选项

整个代码如下所示:

This is a great test! We're testing something awesome. Click here to <a href="whatever">test it!</a>.
/(?<!href="whatever">)test/
$replacement = preg_replace('/(?<!href="SOLUTION HERE">)test/','<span style="color: #FF0000;">test</span>',$replacement);
$replacement=preg_replace(“/(?)test/”,“test”,$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>.
这是一个很棒的测试!我们正在测试一些很棒的东西。单击此处查看。

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

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

模式:
~(?:]*>.]*>(*跳过)(*失败))\b测试\b~s

替换:
\0

代码:()

$string=“这是一个很棒的测试!我们正在测试一些很棒的东西。单击此处查看。”;
$pattern='~(?:]*>.]*>(*跳过)(*失败))\b测试\b~s';
$replace='\0';
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>.
这是一个很棒的测试!我们正在测试一些很棒的东西。单击此处查看。

Wow!这太棒了!这也解决了我遇到的许多其他问题(但没有要求解决),它也没有改变“测试”这个词,这也是非常好的。谢谢你,你太棒了!(我以前从未使用过Dom(只是听说过),反正我有10个这样的词,需要回忆,但我看不到性能问题)。下面是如何向模式中添加更多符合条件的子字符串:看起来我还有一个小问题,因为我希望它能在大多数html标记中工作。我想我可以使用您的代码成功地更改它:嗯,img标签很糟糕,因为我们没有关闭它D