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
JavaScript
x
$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
JavaScript
<a href='some-dynamic-link'>New text</a>
Actual
JavaScript
'New text'
Advertisement
Answer
As you’re already using the capture groups, why not actually use them.
JavaScript
$link = "<a href='some-dynamic-link'>Text to replace</a>";
$newText = "Replaced!";
$result = preg_replace('/(<a.*?>).*?(</a>)/', '$1'.$newText.'$2', $link);