0

我有一个这样的字符串存储在 mysql 表中:

?name1=value1&name2=value2&name3=value3

最初这些数据仅用于将 GET 数据发送到另一个脚本,但现在我发现自己需要它来处理其他事情。

PHP中是否有预定义的函数可以将这些对转换为变量或数组?还是我必须手动完成?

4

2 回答 2

6

(名称不佳的)PHP 函数parse_str可以做到这一点,但您需要先去掉最初的问号。

$arr = array();
parse_str($str, $arr);
print_r($arr);

手册页中提到了此功能的一些注意事项:

  • 如果你在没有第二个数组参数的情况下调用它,它会将值作为局部变量写入当前范围。如果字符串包含可能更改程序中已经存在的变量值的键,这可能很危险。
  • The 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.

于 2013-03-30T06:18:19.107 回答
1

Var_export Might be useful.

$arr=?name1=value1&name2=value2&name3=value3
var_export($arr);
于 2013-03-30T06:22:15.977 回答