Search code examples
phpurlencodeurl-encodinglowercase

urlencode to lower case in PHP


In PHP, when url encoding using urlencode(), the outputted characters are in upper case:

echo urlencode('MyString'.chr(31));
//returns 'MyString%1F'

I need to get PHP to give me back 'MyString%1f' for the above example but not to lower case any other part of the string. in order to be consistent with other platforms. Is there any way I can do this without having to run through the string one character at a time, working out if I need to change the casing each time?


Solution

  • Why would you want to do this at all? F or f, it shouldn't make any difference as percent encoding is ment to be case-insensitive. The only case I could think of would be when creating hashes, however personally I would then convert the whole string to either uppercase or lowercase, ie treat it as case-insensitive.

    Anyways, if you really need to do this, then it should be relatively easy using preg_replace_callback:

    $original = 'MyString%1F%E2%FOO%22';
    $modified = preg_replace_callback('/%[0-9A-F]{2}/', function(array $matches)
    {
        return strtolower($matches[0]);
    },
    $original);
    
    var_dump($modified);
    

    This should give you:

    string(18) "MyString%1f%e2%FOO%22"