Anil Chaudhari
Anil Chaudhari

Reputation: 831

How to replace specific tag with regex 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.

Upvotes: 2

Views: 477

Answers (2)

Toto
Toto

Reputation: 91373

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

Upvotes: 1

user3040610
user3040610

Reputation: 760

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

Upvotes: 3

Related Questions