Take the 2-minute tour ×

i have the following 2 arrays that i am looking to replace variables from. However my problem is how to tell to not replace variables that are in %XX format. Right now 0 will get replaced with %30, and this will then again get replaced with %%330 (replaced 3 with %33). Any help greatly appreciated. Thanks



share|improve this question
Why are you reimplementing urlencode? –  Dan Grossman Dec 15 '10 at 13:55
That way madness lies. –  middaparka Dec 15 '10 at 13:57
The only reason I can think of is that he wants to also encode all the letters/numbers as some kind of exercise. urlencode does not do this. –  thirtydot Dec 15 '10 at 14:00

3 Answers 3

You know you could do that in a cleaner fashion using preg_replace using the e modifier:

echo preg_replace('/([A-Za-z0-9])/e', '"%".dechex(ord("\\1"))', 'Abc');
// outputs %41%62%63

If you want other characters too, just add them into the brackets [], escaping them if necessary, of course.

share|improve this answer
First off, eval is evil. Use preg_replace_callback instead. Second, that doesn't solve the double encoding problem... –  ircmaxell Dec 15 '10 at 14:17
Don't even get me started with this "eval is evil" stuff. It is in some cases, but not this one. The above cannot execute arbitrary PHP code, the input is controlled and is always a single character. –  netcoder Dec 15 '10 at 14:20

Parse the string: Pick one chat at a time and if it equals '%' AND the following to chars are digits ignore rthose three, else replace the current char.

You can set your replacemnt rules with 1 assoziative array:

$replacements= array("A"=>"%41","B"=>"%42"....);
share|improve this answer

I would do it like this:

function myUrlencode($url) {
    $encodedUrl = '';

    foreach (str_split($url) as $char) {
        $encodedUrl .= '%'.dechex(ord($char));

    return $encodedUrl;
share|improve this answer
Wouldnt this encode the digits behind the %? –  Oliver A. Dec 15 '10 at 14:09
@Oliver A.: I think you're working in the wrong direction here. This is encode not decode. –  jwueller Dec 15 '10 at 14:10

Your Answer


