Skip to content
Advertisement

PHP regex – replace all text between a tag

I have a link being outputted on my site, what i want to do is replace the visible text that the user sees, but the link will always remain the same.

There will be many different dynamic urls with the text being changed, so all the example regex that i have found so far only use exact tags like ‘/.*/’…or something similar

Edited for a better example

$link = '<a href='some-dynamic-link'>Text to replace</a>';
$pattern = '/#(<a.*?>).*?(</a>)#/';
$new_text = 'New text';
$new_link = preg_replace($pattern, $new_text, $link);

When printing the output, the following is what i am looking for, against my result.

Desired

<a href='some-dynamic-link'>New text</a>

Actual

'New text'

Advertisement

Answer

As you’re already using the capture groups, why not actually use them.

$link = "<a href='some-dynamic-link'>Text to replace</a>";
$newText = "Replaced!";
$result = preg_replace('/(<a.*?>).*?(</a>)/', '$1'.$newText.'$2', $link);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement