preg_replace 用于替换锚标记的正则表达式,其中 URL 不是 sample.com

preg_replace regex for replacing anchor tag where URL is not sample.com

我有一个 preg_replace 的正则表达式,它替换 href 中存在一些 URL(例如 sample.com)的锚标记。现在我需要的是一个正则表达式,它将替换所有其他不包含一些 URL(例如 sample.com)的锚标记。

这是我的正则表达式:

$rw     =   "Go to hell";
$message    =   "<a href='http://twitter.com'>Twitter</a><br/><a href='http://google.com'>Google</a><br/><a href='http://facebook.com'>Facebook</a>";
$message   =   preg_replace("/<a[^>]*\bhref\s*=\s*'(?:[^']*google.com[^']*|[^][^']*facebook.com[^']*)'>(.*)<\/a>/siU", $rw, $message);

结果是:

Twitter (with link)
Go to hell 
Go to hell 

我需要:

Go to hell
Google (with link)
Facebook (with link)

更改您的正则表达式模式,如下所示(使用 前瞻否定断言 ?!):

...
$message = preg_replace("/<a[^>]*\bhref\s*=\s*'https?:\/\/(www)?(?!(google\.com|facebook\.com))[^']*'>(.*)<\/a>/siU", $rw, $message);

print_r($message);

输出将是:

Go to hell
Google (with link)
Facebook (with link)