如何用链接替换关键字,但只替换 <a> 之外的词

How do I replace a keyword with links but only words outside <a>

我有这段文字 "hi my name is google check out my page" 我想用 link 替换 google 例如 google.com 我使用这个 php 函数 str_replace

代码:

<?php
$text = 'hi my name is google check out my page';
echo str_replace ('google' , '<a href="http://google.com/">google</a>' , $text);

?>

这将输出

hi my name is <a href="http://google.com/">google</a>check out my page

如果我再次 运行 这段代码的问题 输出将重复替换

hi my name is <a href="http://<a href="http://google.com/">google</a>.com/"><a href="http://google.com/">google</a></a>check out my page

我只想替换不在 <a> or <img> 中的文本 请帮忙

您可以从 str_replace 更改为 preg_replace。这样就可以 运行 一个正则表达式来确保 google 之前的值不是 / 或 >.

preg_replace('/(?<![\/>])google/i', '<a href="http://google.com/">google</a>', $text);