Skip to content

Instantly share code, notes, and snippets.

@OldStarchy
Last active June 8, 2023 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OldStarchy/1131111bc921b9f09156e64613bd2a32 to your computer and use it in GitHub Desktop.
Save OldStarchy/1131111bc921b9f09156e64613bd2a32 to your computer and use it in GitHub Desktop.
Similar to parse_str but don't mangle parameters with dots or spaces
<?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