I am trying to convert special characters (eg. +
, /
, &
, %
) which I will use them for a GET request. I have constructed a
Because all your replacements have a percentage (%) character in them, you have to first replace all the occurrences of % with its equivalent %25. Afterwards you should replace other characters such as space and so on. An when you try to convert back the encoded url to its original state, % character should be the last character that you convert back. Convert back your array in reverse order. use array_reverse() function to reverse the order of elements of $specChars. In other words you have to use two separate functions for encoding and decoding your urls.
The following functions are the ones I have written myself to do the job.
$arrayChrs = array('%',' ','!');
$arrayChrs = array('%25', '%20','%21');
function encodeData($subject)
{ //enode data
global $arrayCodes;
global $arrayChrs;
if (!is_null($arrayChrs) && !is_null($arrayCodes)) {
$arCnt1 = count($arrayChrs);
$arCnt2 = count($arrayCodes);
if ($arCnt2 == $arCnt1) {
for ($x = 0; $x <= ($arCnt2 - 1); $x++) {
$code1 = $arrayCodes[$x];
$char1 = $arrayChrs[$x];
$code_encoded = utf8_encode($code1);
$char_encoded = utf8_encode($char1);
$subject = str_replace($char_encoded, $code_encoded, $subject);
}
}
}
return $subject;
}
//[end function]
function decodeData($subject)
{ //decode data
global $arrayCodes;
global $arrayChrs;
$outputStr = $subject;
if (!is_null($arrayChrs) && !is_null($arrayCodes)) {
$arCnt1 = count($arrayChrs);
$arCnt2 = count($arrayCodes);
if ($arCnt2 >= 1 and $arCnt2 == $arCnt1) {
if ($arCnt2 >= 1) {
for ($x = ($arCnt2-1); $x >=0; $x--) {
$code1 = $arrayCodes[$x];
$char1 = $arrayChrs[$x];
$code_encoded = utf8_encode($code1);
$char_encoded = utf8_encode($char1);
$outputStr = str_replace($code_encoded, $char_encoded, $outputStr);
}
}
}
}
return $outputStr;
}
//[end function ]
Notice that one for loop counts elements forward by using $x++, and the other one counts elements in reverse order by using $x--.
Elements in $arrayChrs are replaced by elements in $arrayCodes during encoding. During decoding the reverse replacement takes place.