How to replace hyperlink dynamically using PHP

I want to replace the following hyperlinks dynamically

from

<a href="/xsearch2?q=some search/21">21</a>

to

<a href="/xsearch2?q=some search&page=21">21</a>

how can I do that dynamically

have tried the following

preg_replace('#<a.*?>([^>]*)</a>#i', '<a href="/xsearch2?q='.$key.'&page=$1">$1</a>', $pagination);

but its changing the hyperlinks also, just want to remove the last slash / from hyperlinks and add &page=