views:

118

answers:

2

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>)?

+1  A: 

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

p4bl0
Note that when using `/e`, the replacement script fragment needs to be a string to prevent it from being interpreted before the call to preg_replace: `preg_replace('/.../e', '"char=" . urlencode("$1") . "\\">$1</a>"', $links);`
outis
A: 

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);

Mihail Dimitrov