我有一个这样的字符串存储在 mysql 表中:
?name1=value1&name2=value2&name3=value3
最初这些数据仅用于将 GET 数据发送到另一个脚本,但现在我发现自己需要它来处理其他事情。
PHP中是否有预定义的函数可以将这些对转换为变量或数组?还是我必须手动完成?
我有一个这样的字符串存储在 mysql 表中:
?name1=value1&name2=value2&name3=value3
最初这些数据仅用于将 GET 数据发送到另一个脚本,但现在我发现自己需要它来处理其他事情。
PHP中是否有预定义的函数可以将这些对转换为变量或数组?还是我必须手动完成?
(名称不佳的)PHP 函数parse_str
可以做到这一点,但您需要先去掉最初的问号。
$arr = array();
parse_str($str, $arr);
print_r($arr);
手册页中提到了此功能的一些注意事项:
magic_quotes_gpc
setting affects how this function operates, since this is the routine used internally by PHP to decode query strings and urlencoded POST bodies.If you need a portable solution that is not affected by the magic_quotes_gpc
setting then it's reasonably straightforward to write a decoding function manually, using urldecode
to handle the value encoding:
function parseQueryString($queryString) {
$result = array();
$pairs = explode("&", $queryString);
foreach ($pairs as $pair) {
$pairArr = split("=", $pair, 2);
$result[urldecode($pairArr[0])] = urldecode($pairArr[1]);
}
return $result;
}
This solution will probably be slightly slower than the built-in parse_args
function, but has the benefit of consistent behavior regardless of how PHP is configured. Of course you will again need to first strip off the ?
from the beginning, which is not included in either example.
Var_export Might be useful.
$arr=?name1=value1&name2=value2&name3=value3
var_export($arr);