带函数的preg_replace

I have some HTML that is being run through PHP:

<a href="?char=">&</a>

and I'm wanting to use a preg_replace to replace the first & with a urlencoded value of it. However:

preg_replace("/char=\">(.*?)<\/a>/", "char=".urlencode("$1")."\">$1</a>", $links);

But this gives me the value $1, instead of the expected back-reference. How can I do what I'm trying to do (make the output look like <a href="?char=%26">&</a>)?

You can use the modifier e in your regexp or use the function preg_replace_callback (see the doc) instead.

Yes, both e modifier and preg_replace_callback function approaches can do the job.
I personally prefer one-line decision:

preg_replace("/char=\">(.*?)</a>/e", '"char=".urlencode("$1")."\\">$1"', $links);