问题
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 urlencode
d 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>
)?
回答1:
You can use the modifier e
in your regexp or use the function preg_replace_callback
(see the doc) instead.
回答2:
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);
来源:https://stackoverflow.com/questions/1710764/preg-replace-with-function