Skip to content

Instantly share code, notes, and snippets.

@christianjul
Last active Sep 2, 2015
Embed
What would you like to do?
Version of PHPs parse_str and http_build_query that handles query strings with more than one parameter with the same identifier in the same way as .NET
<?php
namespace christianjul\util;
/** HTTP related utilities */
class HTTP {
/**
* PHP's built-in parse_str cannot properly handle querystrings that have parameters with the same identifier.
*
* This function returns these entries as an array.
*
* @see http://php.net/manual/en/function.parse-str.php#76792
*
* @param $str
*
* @return array
*/
public static function parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
$value = rawurldecode($value);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
/**
* A version of http_build_query that reverses parse_str above
*
* Differences to PHP standard version is that parameter identifiers will be repeated rather than array indexed
* PHP-style
*
* @param array $multiDimensionalArrayOfParameters
*
* @return string
*/
public static function http_build_query($multiDimensionalArrayOfParameters) {
return preg_replace('/%5B[0-9]+%5D/simU', '',
http_build_query($multiDimensionalArrayOfParameters)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment