Let's say you pass some data between the client and the server in a more or less array-like structure.
If using the [] brackets in the field names is not enough (or won't comply with the rest of the project for some reason), you might have to use a string with a number of different delimiters (rows, fields, rows inside fields and such).
To make sure that the data doesn't get mistaken for delimiters, you can use the encodeURIComponent() JavaScript function. It pairs nicely with rawurldecode().
Once the string passed to the server side finally gets exploded into an array (or set of such), you could use the following function to recursively rawurldecode the array(s):
<?php
function rawurldecode_array(&$arr)
{
foreach (array_keys($arr) as $key)
{
if (is_array($arr[$key]))
{
rawurldecode_array($arr[$key]);
}
else
{
$arr[$key] = rawurldecode($arr[$key]);
}
}
}
$a[0] = rawurlencode("2+1:3?9");
$a["k"] = rawurlencode("@:-/");
$a[-3][0] = rawurlencode("+");
$a[-3][2] = rawurlencode("=_~");
$a[-3]["a"] = rawurlencode("this+is a%test");
echo "<pre>"; print_r($a); echo "</pre>";
rawurldecode_array($a);
echo "<pre>"; print_r($a); echo "</pre>";
?>
The program will output:
Array
(
[0] => 2%2B1%3A3%3F9
[k] => %40%3A-%2F
[-3] => Array
(
[0] => %2B
[2] => %3D_%7E
[a] => this%2Bis%20a%25test
)
)
Array
(
[0] => 2+1:3?9
[k] => @:-/
[-3] => Array
(
[0] => +
[2] => =_~
[a] => this+is a%test
)
)
rawurldecode
説明
string rawurldecode ( string str )文字列の中にパーセント記号 (%) に続いて 2 つの 16 進数があるような表現形式を、文字定数に置き換えて返します。
注意: rawurldecode() は、プラス記号 ('+') をスペースに変換しません。urldecode() は変換します。
rawurlencode()、 urldecode() および urlencode() も参照ください。
rawurldecode
Tomek Perlak [tomekperlak at tlen pl]
14-Nov-2006 08:03
14-Nov-2006 08:03
nelson at phprocks dot com
03-Apr-2006 06:18
03-Apr-2006 06:18
This function also decodes utf8 strings so it behaves more like the javascript unscape() function.
<?php
function utf8RawUrlDecode ($source) {
$decodedStr = "";
$pos = 0;
$len = strlen ($source);
while ($pos < $len) {
$charAt = substr ($source, $pos, 1);
if ($charAt == '%') {
$pos++;
$charAt = substr ($source, $pos, 1);
if ($charAt == 'u') {
// we got a unicode character
$pos++;
$unicodeHexVal = substr ($source, $pos, 4);
$unicode = hexdec ($unicodeHexVal);
$entity = "&#". $unicode . ';';
$decodedStr .= utf8_encode ($entity);
$pos += 4;
}
else {
// we have an escaped ascii character
$hexVal = substr ($source, $pos, 2);
$decodedStr .= chr (hexdec ($hexVal));
$pos += 2;
}
} else {
$decodedStr .= $charAt;
$pos++;
}
}
return $decodedStr;
}
?>
php dot net at hiddemann dot org
24-May-2005 06:08
24-May-2005 06:08
To sum it up: the only difference of this function to the urldecode function is that the "+" character won't get translated.