Skip to content

Instantly share code, notes, and snippets.

@mrclay
Created April 4, 2012 20:56
Show Gist options
  • Save mrclay/2305576 to your computer and use it in GitHub Desktop.
Save mrclay/2305576 to your computer and use it in GitHub Desktop.
Alter (or remove) querystring keys from a root-relative URI
<?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