Last active
September 2, 2015 12:59
-
-
Save christianjul/a2f3a3cfd500d0eee837 to your computer and use it in GitHub Desktop.
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
This file contains hidden or 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 | |
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