Encoding ASCII Characters in URL – PHP Solution

By | April 29, 2008

Sometimes you need to encode the whole URL, not just specific characters that are encoded with urlencode(). You might need to represent your query string or anything else as shown at W3C School. There is quite a simple solution in PHP:

<?
$string="some-string";

for ($i=0; $i<strlen($url); $i++)
{
$mass[$i]=”%”.dechex(ord($url{$i}));
}

$encoded_string=implode(“”, $mass);
?>

In the sample provided the string is transformed into an array and then each array element is replaced with its hex representation. Then the array is transformed back to string.

I’ve been searching for this code on the net, but had to write it by myself and I’d like to share it with you.

This will help you to encode urls, form data or anything you like. Just paste the code and add your string! Hope this will help you to develop more efficient sites!