Last active
June 8, 2023 03:23
Similar to parse_str but don't mangle parameters with dots or spaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
/** | |
* Similar to parse_str, parses a query string and returns the resulting array. | |
* Does not replace '.' and ' ' with underscores. | |
* | |
* @param string $string | |
* @return array | |
*/ | |
function parse_query_string($string, ?callable $onError) | |
{ | |
$parts = explode('&', $string); | |
$result = []; | |
foreach ($parts as $part) { | |
if (str_contains($part, '=')) { | |
$off = strpos($part, '='); | |
$name = substr($part, 0, $off); | |
$value = substr($part, $off + 1); | |
$value = urldecode($value); | |
} else { | |
$name = $part; | |
$value = null; | |
} | |
$name = urldecode($name); | |
$fullName = $name; | |
$indexes = []; | |
if (str_contains($name, '[')) { | |
$off = strpos($name, '['); | |
$base = substr($name, 0, $off); | |
$index = substr($name, $off + 1); | |
if ($base === '') { | |
continue; | |
} | |
$name = $base; | |
if (str_contains($index, ']')) { | |
$off = strpos($index, ']'); | |
$idx = substr($index, 0, $off); | |
$index = substr($index, $off + 1); | |
$indexes[] = $idx; | |
while (str_starts_with($index, '[')) { | |
if (str_contains($index, ']')) { | |
$index = substr($index, 1); | |
$off = strpos($index, ']'); | |
$idx = substr($index, 0, $off); | |
$index = substr($index, $off + 1); | |
$indexes[] = $idx; | |
} else { | |
if ($onError !== null) { | |
$onError($fullName, $value); | |
} | |
break; | |
} | |
} | |
} else { | |
if ($onError !== null) { | |
$onError($fullName, $value); | |
} | |
} | |
} | |
if (count($indexes) === 0) { | |
$result[$name] = $value; | |
continue; | |
} | |
array_unshift($indexes, $name); | |
$last = array_pop($indexes); | |
$ref = &$result; | |
foreach ($indexes as $idx) { | |
if ($idx === '') { | |
$ref[] = []; | |
$ref = &$ref[count($ref) - 1]; | |
} else { | |
if (!isset($ref[$idx]) || !is_array($ref[$idx])) { | |
$ref[$idx] = []; | |
} | |
$ref = &$ref[$idx]; | |
} | |
} | |
if ($last === '') { | |
$ref[] = $value; | |
} else { | |
$ref[$last] = $value; | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment