Skip to content

Instantly share code, notes, and snippets.

@andyg1
Created March 11, 2016 18:16
Show Gist options
  • Save andyg1/61da92f3a2b21bc1e749 to your computer and use it in GitHub Desktop.
Save andyg1/61da92f3a2b21bc1e749 to your computer and use it in GitHub Desktop.
// https://gist.github.com/philfreo/1040968
/**
* Add the querystring variable $key with a value $value to $url.
* If $key is already specified within $url, it will replace it.
*
* Based upon http://www.addedbytes.com/code/querystring-functions/
*
* @param string $url
* @param string $key
* @param string[optional] $value
* @return string
*/
function add_querystring_var($url, $key, $value = '') {
$url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
$value = $value ? "=".urlencode($value) : '';
if (strpos($url, '?') === false)
return ($url . '?' . $key . $value);
else
return ($url . '&' . $key . $value);
}
/**
* Remove the Querystring variable $key and its value from the given $url.
* @param string $url
* @param string $key
* @return string
*/
function remove_querystring_var($url, $key) {
$parts = parse_url($url);
$qs = isset($parts['query']) ? $parts['query'] : '';
$base = $qs ? mb_substr($url, 0, mb_strpos($url, '?')) : $url; // all of URL except QS
parse_str($qs, $qsParts);
unset($qsParts[$key]);
$newQs = rtrim(http_build_query($qsParts), '=');
if ($newQs)
return $base.'?'.$newQs;
else
return $base;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment