如何在 php 中用正则表达式替换特定标签?
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>".$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);
假设我的内容中有两个链接。如何找到包含 $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>".$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);