簡體   English   中英

preg_replace regex 用於替換 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM