Encode accented characters of an URL to the hexadecimal version [PHP]

I’m facing an issue with some accented characters (like ‘é’, ‘è’, ‘à’, …) in an URL and I wanted to convert them to an hex value in PHP. I found nothing on Google so I have finally created my own function for my needs :

function encodeURIHex($str) {
  $len=strlen($str);
  $ret="";
  for ($i=0; $i<$len; $i++) {
    $dec = ord($str[$i]);
    if ($dec > 191 && $dec < 256) $ret .= "%".strtoupper(dechex($dec));
    else $ret .= $str[$i];
  }
  return $ret;
}

Example :

encodeURIHex("Mère"); // -> M%E8re

I used this array to find which values of dec version of my char I wanted to use (from 192 to 255 in my case).

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*