Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

PHP Function: Remove a Query String Key=>Value

15 Responses »

I was recently coding a website which relied heavily on query string variables. It was absolutely imperative that I keep the query string clean and not duplicate keys. I needed to find a PHP function that would allow me to remove keys (and their values) easily and reliably. Enter a PHP function I found at Added Bytes:

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

/* usage */
//pretending this page is 

All I needed to do was provide the URL (in my case I wanted the current page's URI) and the key to remove -- so simple!

All credit goes to Added Bytes for their awesome work. It saved me a lot of time...hopefully it does for you too!

Discussion

  1. January 15, 2010 @ 11:39 am

    I needed something like this also in a projet.
    This is what I came up with


    $qStr = "varOne=1&varTwo=2&key_to_remove=3&varFour=4"; //$_SERVER['QUERY_STRING']
    $key="key_to_remove";
    parse_str($qStr,$ar);
    echo http_build_query(array_diff_key($ar,array($key=>"")));
    //Outputs : varOne=1&varTwo=2&varFour=4

    Not sure what’s the performance difference though

  2. January 15, 2010 @ 2:01 pm

    I have a very similar function to yours, David, and it seems for nearly the same reason.

    function remove_qs_key($url, $key) {
    $url = preg_replace('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', "$1", $url);
    return $url;
    }

  3. amitay
    January 15, 2010 @ 3:13 pm

    I would use preg_quote() on the key…

  4. dutchie
    January 16, 2010 @ 5:29 pm

    When do you need to remove a key from a query string? Just curious, since I never needed to and been using php quite long.

  5. ken marfilla
    January 17, 2010 @ 7:24 pm

    @Phil Pérusse:

    I think unset will be much faster than array_diff if you’re only removing a few keys.

  6. trippo
    January 18, 2010 @ 2:37 am

    Hi,

    I use a similar function sometimes – but it does more than just remove a certain key. The purpose of the function is to build the querystring entirely. It takes two parameters, one array containing keys (with values) that should be added to the querystring and one array containing keys that should be removed. Then it cycles through the current querystring and removes or keeps keys depending on the parameter and finally adds keys if there are any.

    Maybe this approach isn’t as good in your case but I’ve found it to be quite useful when I have a site that’s depending on querystring entirely.

    // trippo

  7. tiziano zonta
    January 22, 2010 @ 6:18 pm

    the function don’t works if I want to remove first key of my query string

    $query_string = “page=home&lang=it”;
    echo remove_querystring_var($query_string,’page’); //not works
    echo remove_querystring_var($query_string,’lang’); //works

  8. January 30, 2010 @ 1:46 am

    thanks, that’s cool :)

  9. February 15, 2010 @ 3:40 pm

    Hi,

    nice code, but it did not work for the first parameter, because the “?” should be escaped: “\?” to match.
    See here: http://php.net/manual/de/function.preg-replace.php

    if i add escape it works for me:

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

    echo remove_querystring_var(“http://www.thinkplexx.com/?errors=%0A%09The+password+field+is+empty.%3B”,”errors”);

  10. February 15, 2010 @ 8:40 pm

    Still that entire regex could be reduced to:

    preg_replace(‘/(?:&|(\?))’ . $key . ‘=[^&]*(?(1)&|)?/i’, “$1″, $url);

  11. February 28, 2010 @ 2:57 pm

    I like the parse_str/http_query_build idea so I extended it to include the ability to remove an array of values and add an array of values.

    function querystring($strQS, $arRemove, $arAdd = NULL)
    {
    parse_str($strQS, $arQS);
    $arQS = array_diff_key($arQS, array_flip($arRemove));
    $arQS = $arQS + $arAdd;
    return http_build_query($arQS);
    }

    Example:
    Current URL = http://www.example.com?one=1&two=2&three=3&four=4

    $arR = array(‘two’, ‘four’);
    $arA = array(‘five’ => 5, ‘six’ => 6);
    echo querystring($_SERVER['QUERY_STRING'], $arR, $arA);

    prints “one=1&three=3&five=5&six=6″

  12. adam
    May 5, 2010 @ 9:04 am

    @Dustin Hansen: Dustin’s solution is the most elegant and I found the other solutions to have issues with parameter’s at the beginning and end of the query string – in my testing Dustin’s solution worked for parameters at all positions.

  13. adam
    May 5, 2010 @ 9:05 am

    @Adam: Oh and just for making it even more condensed, shorten the whole function to this:

    function remove_qs_key($url, $key) {
    return preg_replace(‘/(?:&|(\?))’ . $key . ‘=[^&]*(?(1)&|)?/i’, “$1″, $url);
    }

  14. charlie
    June 28, 2010 @ 2:16 pm

    I had an array of checkbox values being passed in the querystring, and I don’t think these functions work for removing it.

    I found it easier to just directly define the $_SERVER['QUERY_STRING'] by concatenating the $_GET[] variables I wanted to pass, and leaving out the ones I didn’t (the checkbox array)

  15. charlie
    June 28, 2010 @ 2:17 pm

    I had an array of checkbox values being passed in the querystring, and I don’t think these functions work for removing it.

    I found it easier to just directly define the $_SERVER['QUERY_STRING'] by concatenating the $_GET[] variables I wanted to pass, and leaving out the ones I didn’t (the checkbox array)

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!