Php 用于排除由特殊字符包围的单词的正则表达式

Php 用于排除由特殊字符包围的单词的正则表达式,php,regex,preg-replace,Php,Regex,Preg Replace,我一直在为我遇到的一个正则表达式难题寻找解决方案 最近,我参与了一个项目,我们需要用锚定标记列表替换给定文本中的单词列表 例如,给定一个字符串 This is a test string 我可能想把“测试”一词替换为 <a target="_blank"  href="https://website.com/string-random“>test</a>. 在某些情况下,锚定标记中的一些URL包含可能被替换的单词 例如,给定要替换的单词列表
 [ {

我一直在为我遇到的一个正则表达式难题寻找解决方案

最近,我参与了一个项目,我们需要用锚定标记列表替换给定文本中的单词列表

例如,给定一个字符串

This is a test string
我可能想把“测试”一词替换为

<a target="_blank"  href="https://website.com/string-random“>test</a>. 
在某些情况下,锚定标记中的一些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>
这是一个
目前,我正在寻找一个正则表达式,它不会匹配任何由特殊字符包围的单词,因为我认为这将解决我的问题


对于如何解决此问题的任何其他想法也非常开放

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

换言之,您希望替换在next<发生在next>之前的某些字符后面的字符串(标记之间的字符串,而不是标记内的字符串)

因此,试试这个:
(要匹配的字符串)(?=[^>]*?,根据需要多次,然后尝试:

foreach($wordlist作为$word){

$document=preg_replace(“~(?!)($word[keyword])(?!)~i”,“$1我发现一种模式对我来说非常有效
$pattern='/(?\/-)\b.preg\u quote($stringToReplace,'/')。\b(?)(
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>
foreach ($wordlist as $word){
     $document = preg_replace("~(?! )($word[keyword])(?! )~i","<a href='$word[link]'>$1<")
}