我总是通过$ _SERVER ['QUERY_STRING']或$ _SERVER ['REQUEST_URI']获取查询字符串和路径, 但有时这会得到无效的价值,
#1
?a[]=1&b[]=2
(should be: ?a%5B%5D=1&b%5B%5D=2)
#2
?c%5B%5D=3&d[]=4
(should be: ?c%5B%5D=3&d%5B%5D=4)
#3
/to/path*/a/1
(should be: /to/path%2A/a/1)
#4
/to/path%2A/a*/1
(should be: /to/path%2A/a%2A/1)
如何始终将字符串编码?如果使用urlencode()是个坏主意,因为某些字符已编码或不应编码。
答案 0 :(得分:1)
不是最干净的解决方案,但目前这是我唯一能想到的:
function parse ($string, $allowed = array('?', '=', '/')) {
$chars = str_split(urldecode($string));
$encoded = '';
foreach ($chars as $char) {
if (in_array($char, $allowed)) {
$encoded .= $char;
continue;
}
$encoded .= urlencode($char);
}
return $encoded;
}
演示:http://codepad.org/QKFSWmHs
首先,字符串被解码以对其进行规范化(我们是否应该担心双重编码?)。之后我们简单地遍历所有字符并检查字符是否应该被编码。