Regex表达式以排除特殊字符包围的单词

问题描述 投票:0回答:2

我一直在寻找解决我遇到的正则表达式难题的问题。

最近,我在一个项目中工作,我们需要用锚标签列表替换给定文本中的单词列表。

例如,给定一个字符串

This is a test string

我可能想用]代替“测试”一词>

<a target="_blank"  href="https://website.com/string-random“>test</a>. 

结果字符串应该看起来像这样

This is a <a target="_blank" href="https://website.com/string-random“>test</a> string

单词的替换在一个循环中完成

foreach ($documents as $document)
 
    foreach ($links as $link)
        replace keywords

在某些情况下最终会发生的是锚标记中的某些URL包含可能被替换的单词

例如,给定要替换的单词列表

[
    {
        'keyword': 'test',
        'link': 'https://website.com/string-random'
    },
    {
        'keyword': 'string',
        'link': 'https://random.com/string'
    }
]

完成所有替换后,我在上面给出的示例字符串看起来像这样

This is a <a target="_blank" href="https://website.com/<a target="_blank"  href="https://random.com/string“>string</a>-random“>test</a> <a target="_blank" href="https://random.com/string“>string</a>

代替

This is a <a target="_blank" href="https://website.com/string-random“>test</a> <a target="_blank" href="https://random.com/string“>string</a>

[目前,我正在寻找一个正则表达式,该正则表达式与用特殊字符包围的任何单词都不匹配,因为我认为这可以解决我的问题。

也非常欢迎任何其他有关如何解决此问题的想法

我在寻找正则表达式难题的解决方案时遇到了问题。最近,我从事一个项目,我们需要用锚标签列表替换给定文本中的单词列表。 ...

php regex preg-replace
2个回答
0
投票

这不仅与以前的替换有关:标记属性/名称/值中出现的任何单词都是一个问题。


0
投票

尝试:

© www.soinside.com 2019 - 2024. All rights reserved.