[英]php preg_replace href attribute using conditions
你好,我有以下標簽:
$content ='<a href="http://website.com/" />
<a href="/link1" />
<a href="https://website.com" />
<a href="link1" />';
和這段代碼:
preg_replace('~href=(\'|"|)(.*?)(\'|"|)(?<!\/|http:\/\/|https:\/\/)~i', 'href=$1http://website2.com/$2$3', $content);
我想使用上面的代碼來替換不以 http 或 https 或以 slash 開頭的 href 標簽。
提前致謝。
像這樣的事情應該這樣做。 我建議將來使用解析器, 您如何在 PHP 中解析和處理 HTML/XML? ,但對於此類任務。 這會很快變得非常混亂。 這里還有一個關於這個正則表達式用法的鏈接, http://www.rexegg.com/regex-best-trick.html 。
正則表達式:
/href=("|')https?:\/\/(*SKIP)(*FAIL)|href=("|')(.*?)\2/
演示: https : //regex101.com/r/cV2xB5/1
PHP 用法:
$content ='<a href="http://website.com/" />
<a href="/link1" />
<a href="https://website.com" />
<a href="link1" />';
echo preg_replace('/href=("|\')https?:\/\/(*SKIP)(*FAIL)|href=("|\')\/?(.*?)\2/', 'href=$2http://website2.com/$3$2', $content);
輸出:
<a href="http://website.com/" />
<a href="http://website2.com/link1" />
<a href="https://website.com" />
<a href="http://website2.com/link1" />
更新,用於//
排除
用:
href=("|')(?:https?:)?\/\/(*SKIP)(*FAIL)|href=("|')(.*?)\2
演示: https : //regex101.com/r/cV2xB5/2
PHP:
$content ='<a href="//website.com/" />
<a href="/link1" />
<a href="https://website.com" />
<a href="link1" />';
echo preg_replace('/href=("|\')(?:https?:)?\/\/(*SKIP)(*FAIL)|href=("|\')\/?(.*?)\2/', 'href=$2http://website2.com/$3$2', $content);
輸出:
<a href="//website.com/" />
<a href="http://website2.com/link1" />
<a href="https://website.com" />
<a href="http://website2.com/link1" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.