A couple of potentially useful PHP functions:
Add Querystring Variable
A PHP function that will add the querystring variable $key with a value $value to $url. If $key is already specified within $url, it will replace it.
function add_querystring_var($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);
}
}
Remove Querystring Variable
A PHP function that will remove the variable $key and its value from the given $url.
function remove_querystring_var($url, $key) {
$url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
return ($url);
}

42 Comments
I can't think of any current use for this... but I know somewhere I'll want something just like this. Thanks for the awesome tip.
#1, Ben Cochran, United States, 6 December 2006. Reply to this.
You may want to add a SupportsMultiple overload..there are times when you need to have multiple values for a single variable (think checkboxes)
all in all..great code!
#2, Evan, United States, 6 December 2006. Reply to this.
Nice... short and sweet! I did some similar a year or so ago for a Smarty plugin....
http://www.phpinsider.com/smarty-forum/viewtopic.php?t=4356
#3, Mark Mitchenall, United Kingdom, 8 December 2006. Reply to this.
Thanks! I have added this to my library of code snippets.
#4, Brett Batie, United States, 11 December 2006. Reply to this.
something like this is really good when you want to create paging for a large dataset and you need to pass narrowing elements along so your script knows what to leave out, or add to the query. I wrote something like this but made it a object so I can alter the existing querystring by only passing some items or ignoring others.
#5, Ernest Leitch, United States, 15 December 2006. Reply to this.
Pretty good stuff, added to my snippets.
#6, milo, Unknown, 18 December 2006. Reply to this.
Could be great to think about something similar for SEO urls where parameters are separated by "/".
#7, Stefan, Czech Republic, 14 January 2007. Reply to this.
Interesting. I wrote something similar. Here's mine.
<?php
/**
* Merge $vars with the current query string, overwriting any
* duplicate variables. Uses arg_seperator.output ini setting to
* determine what to use as an arg seperator.
*
* @param array $vars Variables to add into or replace in the query
* string. Just like $_GET (its merged with $_GET, actually).
*
* @return string A new query string
*
* Usage:
*
* <a href="<?php echo $_SERVER["PHP_SELF"] . "?" .
* querystring_merge("offset" => $offset + $limit); ?>">Next</a>
*
*/
function querystring_merge ( $vars = array() )
{
$sep = ini_get('arg_separator.output');
$qs = "";
foreach ( array_merge($_GET, $vars) as $k => $v ) {
$qs .= "$k=" . urlencode($v) . $sep;
}
return substr($qs, 0, -1); /* trim off trailing $sep */
}
/**
* Remove $remove_vars from query string.
*
* @param mixed $remove_vars string of variable to remove, or array of
* variables
*
* @return string The querystring with the variables from $remove_vars
* removed.
*
* Usage:
* Suppose $_SERVER['QUERY_STRING'] looks like this: ?a=1&b=2&c=3:
*
* echo querystring_remove("a"); -> ?b=2&c=3 (a is removed)
* echo querystring_remove(array("a", "c")); -> ?b=2 (a and c are removed)
*/
function querystring_remove ( $remove_vars )
{
if ( !is_array($remove_vars) ) {
$remove_vars = array($remove_vars);
}
$sep = ini_get('arg_separator.output');
$qs = "";
foreach ( $_GET as $k => $v ) {
if ( !in_array($k, $remove_vars) ) {
$qs .= "$k=" . urlencode($v) . $sep;
}
}
return substr($qs, 0, -1); /* trim off trailing $sep */
}
?>
#8, Anonymous, United States, 21 March 2007. Reply to this.
God i love this site! Just gives us free tips and tricks for development. Thanks Dave!
#9, Chet, Unknown, 6 April 2007. Reply to this.
Nice!
Thank you for all these great articles or whatever I shall call them :D
#10, Anders Men, Norway, 12 April 2007. Reply to this.
Although it does something different, this function might be of use for people landing on this page looking for the php query string function:
http://www.php.net/manual/en/function.http-build-query.php
the http_build_query function will take an array and generate a query string using the array's keys and values.
#11, Stereo, Unknown, 2 May 2007. Reply to this.
Thank you very much, I've already useing this function on my websites.
I don't want to post a lot of comments, so I want to say you thank you for your cheat sheets - they're very useful and helpful!
#12, Shimon, United States, 6 May 2007. Reply to this.
Nice work. It's always a pain trying to juggle them darn queries.
#13, Jason, United States, 16 May 2007. Reply to this.
It's a very usefully functions, no question. It would be easier though to change the arguments in the add_querystring_var() function to accept the key-value pairs as an array.
Nice work.
#14, PHP help, Romania, 26 July 2007. Reply to this.
thank you so much... that repeat functions were really a pain in the ass until this article, you helped a lot!
#15, Okan, Unknown, 26 August 2007. Reply to this.
This is EXACTLY what i needed... quick and perfect. Tried doing it myself with splitting an array and the using in_array, but this is much simpler. Thanks so much
#16, Peter, United States, 11 September 2007. Reply to this.
It would be good if something like this was added to PDO. I was a bit dissapointed with the bindParam and bindValue functions.
#17, David Hopkins, United Kingdom, 14 September 2007. Reply to this.
Hey great tutorial. thanks for sharing.
#18, Introduction to PHP, United Kingdom, 22 September 2007. Reply to this.
I use a similar thing, but I do it based off the current $_GET variables. That way you can easily pass certain ones along, and remove certain ones. Plus it makes it easier as there's no REGEXP involved.
#19, Lewis, United Kingdom, 24 September 2007. Reply to this.
Thanks, a useful code snippet. Saved me having to mess around with regexp!
#20, Paul, United Kingdom, 6 October 2007. Reply to this.
How can I simply remove the entire query string? So, for example, if the user types this URL in their browser address bar...
http://example.com/page.php?a=b
...they would get back this URL in their browser address bar:
http://example.com/page.php
I want it to remove *any* query string (not just "a=b"). And I want it to remove the question mark.
#21, PHP Newbie, United States, 4 December 2007. Reply to this.
Great functions, many thanks.
Would be nice if it could 'Add/Update' or 'Remove' query vars even if they are emptystring. eg...
http://test.com/page.php?key1=val1&key2=&key3=val3
...using your function to 'add/update' 'key2' (whose value is emptystring) will add a new 'key2' to the end of returned querystring?!
also if 'remove' function is used on the above example 'key2' won't get removed. just a thought....
#22, Adz, United Kingdom, 20 February 2008. Reply to this.
I want to know how I can pick a div that contais a table with javascript, pull it into a php variable....
thanks
#23, aioria, United States, 5 April 2008. Reply to this.
good work. sopton and damn clear. It's always a pain trying to juggle them darn queries.
#24, Fay Webber, United Kingdom, 15 April 2008. Reply to this.
thank you so much very good!
#25, DazzleCat, United Kingdom, 8 May 2008. Reply to this.
Thank you. I use these functions a lot, mainly for search filtering (a la Newegg).
#26, kevin, United States, 21 July 2008. Reply to this.
perfect - exactly what I was looking for!
#27, Rob Williams, United Kingdom, 7 August 2008. Reply to this.
Great and compact utility. I have only one question: it does not work with URL params with multiple values, like ¶m[]=value1¶m[]=value2
Any idea how to adapt it, at least for removing params? It would be nice to be able to simply remove all occurences of "param[]=value".
Thanks.
#28, moose, France, 16 September 2008. Reply to this.
Nice precise article, has helped a lot. I've had problems trying to add querystring functions in the past.
#29, Firebubble Design, United Kingdom, 17 September 2008. Reply to this.
Perfect. Exactyl what I am looking for Thanks a lot
#30, coder, Australia, 22 October 2008. Reply to this.
Great functions, Thks.
( It would be perfect in a little class ? like url->add ... )
#31, Lamaison, France, 23 October 2008. Reply to this.
Cheers for the code. Think I'll stick around!
#32, Cambridge Photographer, United Kingdom, 30 October 2008. Reply to this.
this is exactly what i needed. Thanks.
#33, Axthos, Mexico, 17 November 2008. Reply to this.
This was very helpfull thanks!
#34, nulll, Italy, 10 February 2009. Reply to this.
Great!
Exactly what I was looking for.
Thanks!
#35, Gorka, Mexico, 5 March 2009. Reply to this.
Here's my improved, one line implementation of the above example. I'm also catching multiple instances of the key and the case when the key has no value, e.g.
http://test.com/page.php?key1=
or
http://test.com/page.php?key1=val1&key2=&key3=
function remove_querystring_var($url, $key) {
$url = preg_replace('/[\?|&]'.$key.'=[a-zA-Z0-9]*$|'.$key.'=[a-zA-Z0-9]*[&]/', '', $url);
return ($url);
}
#36, Donny, Canada, 11 March 2009. Reply to this.
Here's my improved, one line implementation of the above example. I'm also catching multiple instances of the key and the case when the key has no value, e.g.
http://test.com/page.php?key1=
or
http://test.com/page.php?key1=val1&key2=&key3=
function remove_querystring_var($url, $key) {
$url = preg_replace('/[\?|&]'.$key.'=[a-zA-Z0-9]*$|'.$key.'=[a-zA-Z0-9]*[&]/', '', $url);
return ($url);
}
#37, Donny, Canada, 11 March 2009. Reply to this.
Thanks! This was a real help to me
#38, morehawes, United Kingdom, 14 May 2009. Reply to this.
Thank you so much. just what i needed! :)
#39, fms, Turkey, 20 July 2009. Reply to this.
I get duplicate instances of urls with following strings at the end:
?quicktabs_1=0, ?quicktabs_2=0, etc. There are usually 4 to 5 duplicate instances being generated for the single URL. I need a fix to remove those querystrings from the end. How can I do that? Is the solution provided by Donny above good enough to fix the issue? Does I need to change the string Key to quicktabs there?
#40, Expertscolumn, India, 19 September 2009. Reply to this.
Oh, god! That's just what I was looking for!!!
I spent so much time looking for such function!
THANKYOU!
#41, Tomás Barão, Portugal, 2 October 2009. Reply to this.
Well that's very useful for our site, thanks a lot!
P.S.: Sorry for the double post.
#42, Peter Schmuck, Germany, 1 November 2009. Reply to this.