Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add and remove querystring variables from URLs.
<?php
/*
Add and remove querystring variables from URLs.
*/
function addQuerystringVar($url, $key, $value) {
$url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
if (strpos($url, '?') === false) {
return ($url . '?' . $key . '=' . $value);
} else {
return ($url . '&' . $key . '=' . $value);
}
}
function removeQuerystringVar($url, $key) {
$url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
return ($url);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment