The (poorly-named) PHP function parse_str can do this, though you will need to first trim off the initial question mark.
$arr = array();
parse_str($str, $arr);
print_r($arr);
There are some caveats to this function alluded to in the manual page:
- If you call it without the second array parameter it will write the values into the current scope as local variables. This can be dangerous if the string contains keys that may change the value of variables already present in your program.
- 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.