Anil Chaudhari Anil Chaudhari - 10 days ago 6
PHP Question

How to replace specific anchor tags with strings in php?

Suppose I have two links in my content. How can I find the specific links containing the

$string
and replace with words only.

$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);


I have tried with
'~<a.+href="(.*)".*> '.$string.'</a>~'
but its removing all the content between those anchors too.

Whats wrong ?

update:



replace
<a href="another-link"> dog</a>
with
dog
only and leave
<a href="some-link"> fox</a>
as it is.

Answer

Just use lazy quantifier, ie ?, and add delimiter to the regex:

$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  __^

You could also reduce to:

$new_content =  preg_replace("~<a[^>]+>\s*$string\s*</a>~", $string, $content);