2

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.

2 Answers 2

3
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);
Sign up to request clarification or add additional context in comments.

2 Comments

@AnilChaudhari ,yes fox will be replaced with dog. a quick brown <a href="some-link"> dog</a> jumps over a lazy <a href="another-link"> dog</a>
Thanks for your great answer. But I just want to find anchor tag with selected string and replace the anchor tag element with given string.
1

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

1 Comment

@AnilChaudhari: Sorry, you have to add optional spaces arround $string, see my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.