【问题标题】:Regex: How not to replace specific word in any html tag?正则表达式:如何不替换任何 html 标签中的特定单词?
【发布时间】:2020-06-03 17:37:48
【问题描述】:

假设我有这样的文本:

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

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

/(?<!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】:

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

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

    模式:~(?:&lt;[^&gt;]*&gt;.*?&lt;/[^&gt;]*&gt;(*SKIP)(*FAIL))|\btest\b~s

    替换:&lt;span style="color: #FF0000;"&gt;\0&lt;/span&gt;

    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>.
    

    【讨论】:

    • 哇!这很棒!这也解决了我遇到的许多其他问题(但没有要求修复它们),它也不会改变“测试”这个词,这也非常棒。谢谢你,你真棒! (我之前没用过Dom(只听说过),反正我有10个这样的字,需要recolor,但没看到性能问题)。
    • 我的目标是取悦。以下是向模式添加更多合格子字符串的方法:regex101.com/r/6ZVANT/2
    • 看起来我还有一点问题,因为我希望它可以在大多数 html 标签中工作。我想我可以使用您的代码成功更改它:regex101.com/r/6ZVANT/4
    • 嗯,img 标签很烂,因为我们没有关闭它。 :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多