Skip Navigation

Querystring Functions

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.

  1. function add_querystring_var($url, $key, $value) {
  2. $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
  3. $url = substr($url, 0, -1);
  4. if (strpos($url, '?') === false) {
  5. return ($url . '?' . $key . '=' . $value);
  6. } else {
  7. return ($url . '&' . $key . '=' . $value);
  8. }
  9. }

Remove Querystring Variable

A PHP function that will remove the variable $key and its value from the given $url.

  1. function remove_querystring_var($url, $key) {
  2. $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
  3. $url = substr($url, 0, -1);
  4. return ($url);
  5. }

27 comments

Ben Cochran
United States #1: December 6, 2006
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.
 United States #2: December 6, 2006
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!
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
Thanks! I have added this to my library of code snippets.
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.
Pretty good stuff, added to my snippets.
Could be great to think about something similar for SEO urls where parameters are separated by "/".
Anonymous
United States #8: March 21, 2007
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 */
}

?>
God i love this site! Just gives us free tips and tricks for development. Thanks Dave!
Nice!

Thank you for all these great articles or whatever I shall call them :D
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.
 United States #12: May 6, 2007
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!
Jason
United States #13: May 16, 2007
Nice work. It's always a pain trying to juggle them darn queries.
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.
Okan
Unknown #15: August 26, 2007
thank you so much... that repeat functions were really a pain in the ass until this article, you helped a lot!
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
It would be good if something like this was added to PDO. I was a bit dissapointed with the bindParam and bindValue functions.
Introduction to PHP
United Kingdom #18: September 22, 2007
Hey great tutorial. thanks for sharing.
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.
 United Kingdom #20: October 6, 2007
Thanks, a useful code snippet. Saved me having to mess around with regexp!
PHP Newbie
United States #21: December 4, 2007
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.
Adz
United Kingdom #22: February 20, 2008
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....
aioria
United States #23: April 5, 2008
I want to know how I can pick a div that contais a table with javascript, pull it into a php variable....
thanks
good work. sopton and damn clear. It's always a pain trying to juggle them darn queries.
 United Kingdom #25: May 8, 2008
thank you so much very good!
kevin
United States #26: July 21, 2008
Thank you. I use these functions a lot, mainly for search filtering (a la Newegg).
Rob Williams
United Kingdom #27: August 7, 2008
perfect - exactly what I was looking for!

Post Your Comment

· Comments with keywords instead of a name have their URLs removed.
· Your email address will not be displayed or shared.
· "Remember Me" is disabled - caching is on due to high server load.

Live Comment Preview

 #28: 1 minute ago