php preg_replace要链接的单词,但是单词不能作为锚点的一部分

时间:2022-04-08 16:49:17

I have some HTML content:

我有一些HTML内容:

<p>
Nunc nulla tincidunt metus sed eros auctor sagittis. Sed malesuada, mi et ornare 
molestie, urna dui 
<a href="http://google.com/" title="condimentum nulla">condimentum nulla, ut luctus</a> nisl ipsum ut dui. 
Praesent aliquam velit quis neque congue consectetur <b>nulla</b>. 
Curabitur turpis risus, malesuada nec volutpat sit amet, auctor porta velit.
</p>

And i want to replace all "nulla" words to links, but only if "nulla" is not a part of another link url or other HTML parameter (title, alt). In above example script should only replace first and last "nulla" word, and others leave as is. I'm stuck with this regular expression, but it doesn't work how i want:

我想将所有“nulla”单词替换为链接,但前提是“nulla”不是另一个链接url或其他HTML参数(title,alt)的一部分。在上面的示例中,脚本应该只替换第一个和最后一个“nulla”单词,而其他单词则保持原样。我坚持使用这个正则表达式,但它不符合我的要求:

/[^<a]+[^>]*nulla[^<\/a>]/

1 个解决方案

#1


3  

Final solution that works as it should:

最终解决方案应该按原样运行:

$str = preg_replace('~\bnulla\b(?!(?>[^<]*(?:<(?!/?a\b)[^<]*)*)</a>)~iu', '<a href="novo-mega-link.php">$0</a>', $str);

#1


3  

Final solution that works as it should:

最终解决方案应该按原样运行:

$str = preg_replace('~\bnulla\b(?!(?>[^<]*(?:<(?!/?a\b)[^<]*)*)</a>)~iu', '<a href="novo-mega-link.php">$0</a>', $str);