urlencode not parsing \$2 in preg_replace - htmlentities is

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

urlencode not parsing \$2 in preg_replace - htmlentities is

Post by anjanesh »

I have

Code: Select all

$val = preg_replace(
     array("/(<img src=\")(.*?)(\")/is"),
     array("\$1myimage.php?filename=".urlencode("\$2")."\$3"),
     $val
);
If I replace urlencode with htmlentities, \$2 gets converted to the SRC of the IMG tag.
Problem is that IMG SRC has a url in it like <IMG SRC="http://originaldomain.com?url=imagelocationdomain">

On using htmlenities I get

Code: Select all

<img src="myimage.php?filename=http://originaldomain.com?url=imagelocationdomain">
but on using urlencode I get

Code: Select all

<img src="myimage.php?filename=http%253A%252F%252Foriginaldomain.com%25242">
when urldecoded src is myimage.php?filename=http://originaldomain.com$2
when it should have been myimage.php?filename=http://originaldomain.com?url=imagelocationdomain

Problem : \$2 is not getting parsed when using urlencode - but its getting parsed when using htmlentities.

Any ideas why ?

Thanks.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Have a look at example 5 at http://www.php.net/preg_replace.

But i would suggest you use http://www.php.net/preg_replace_callback (Ask phpBB why the e modifier can be dangerous :p)
Post Reply