[英]How to replace specific tag with regex in php?
假設我的內容中有兩個鏈接。 如何找到包含$string
的特定鏈接並僅替換為單詞。
$string = 'dog';
$content = 'a quick brown <a href="some-link"> fox</a> jumps over a lazy <a href="another-link"> dog</a>';
$new_content = preg_replace('<a.+href="(.*)".*> '.$string.'</a>', $string, $content);
我嘗試使用'~<a.+href="(.*)".*> '.$string.'</a>~'
但是它也刪除了這些錨點之間的所有內容。
怎么了 ?
更換<a href="another-link"> dog</a>
與dog
只有離開<a href="some-link"> fox</a>
,因為它是。
Try this to replace the anchor text to given string with preg_replace,
$string = 'dog';
$content = 'a quick brown <a href="some-link"> fox</a> jumps over a lazy <a href="another-link"> dog</a>';
echo preg_replace('/<a(.+?)>.+?<\/a>/i',"<a$1>".$string."</a>",$content);
只需使用惰性量詞,即?
,並將定界符添加到正則表達式中:
$string = 'dog';
$content = 'a quick brown <a href="some-link"> fox</a> jumps over a lazy <a href="another-link"> dog</a>';
$new_content = preg_replace('~<a.+?href="(.*?)".*> '.$string.'</a>~', $string, $content);
// here ___^ and __^
您還可以簡化為:
$new_content = preg_replace("~<a[^>]+>\s*$string\s*</a>~", $string, $content);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.