Created
April 4, 2012 20:56
-
-
Save mrclay/2305576 to your computer and use it in GitHub Desktop.
Alter (or remove) querystring keys from a root-relative URI
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 | |
/** | |
* Alter (or remove) querystring keys from a root-relative URI. | |
* @param array $values associative array (see http_build_query). Use null value to remove keys | |
* @param string $uri if not given, $_SERVER['REQUEST_URI'] will be used | |
* @return string | |
*/ | |
function alterQueryString($values = array(), $uri = null) { | |
$parts = parse_url($uri ? $uri : $_SERVER['REQUEST_URI']); | |
$query = array(); | |
if (isset($parts['query'])) { | |
parse_str($parts['query'], $query); | |
} | |
$query = array_merge($query, $values); | |
$qs = http_build_query($query, null, '&'); | |
return $parts['path'] . ($qs ? "?$qs" : ''); | |
} | |
// /hello => /hello?sort=title | |
// /hello?abc=123 => /hello?abc=123&sort=title | |
$uri = alterQueryString(array('sort' => 'title')); | |
// /hello?abc=123 => /hello | |
// /hello?abc=123&sort=title => /hello?sort=title | |
$uri = alterQueryString(array('abc' => null)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment