Last active
August 2, 2016 09:27
-
-
Save Tiriel/3c6bd5bf75dced2c899582f8ab13d278 to your computer and use it in GitHub Desktop.
Custom function for URL parsing
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 | |
/** | |
* Custom version of parse_str function to avoid overriding of multiple definitions in query string | |
* | |
* @param $string | |
* @return array | |
*/ | |
function proper_parse_str($string) | |
{ | |
$array = array(); | |
$delimiter = '?'; | |
// Determining string delimiter | |
if (strpos($string, '?') === false) { | |
$delimiter = '/'; | |
} | |
// URL decoding and checking string length. If single query, return simple array | |
$string = urldecode(substr($string, strrpos($string, $delimiter)+1)); | |
if (strpos($string, '=') === false) { | |
$array[$string] = $string; | |
return $array; | |
} | |
// Building query array. First explode: extracting parameters | |
$pairs = explode('&', $string); | |
foreach ($pairs as $pair) { | |
// Second explode: getting key-value pairs from paramaters | |
list($key, $value) = explode('=', $pair, 2); | |
// Checking if key already exist. | |
if (isset($array[$key])) { | |
// If key exists | |
if (is_array($array[$key])) { | |
// And if it's already an array, value is added | |
$array[$key][] = $value; | |
} else { | |
// If not, key is transformed in array and new value is added | |
$array[$key] = array($array[$key], $value); | |
} | |
} else { | |
// If key doesn't exists, key-value pair is added to master array | |
$array[$key] = $value; | |
} | |
} | |
return $array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment