Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex - replace all text between a tag

Tags:

regex

php

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'
like image 993
Key Avatar asked Jul 15 '26 03:07

Key


1 Answers

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);
like image 61
nicael Avatar answered Jul 17 '26 16:07

nicael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!