1

Expanding on my original question here: I would now like to remove more than 1 variable from the querystring.

For example, I want to remove the variables bar1 & bar2 from the querystring. I have tried the following code:

echo parseQueryString("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],"bar2","bar1");

But this doesn't remove both variables, only bar2.

Any help appreciated.

Thank you,

Matt

Community
  • 1
  • 1
Matt
  • 345
  • 1
  • 6
  • 16

4 Answers4

3

I would use

  • parse_str($_SERVER["QUERY_STRING"], $array); to take apart the query string

  • unset($array["bar1"]); to remove the unwanted variables

  • http_build_query($array); to glue the query string back together

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
2

You'll be wanting something like

echo parseQueryString(parseQueryString("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],"bar2"),"bar1");

Alternatively, since I'm assuming parseQueryString is a function you defined, you can change it so it accepts an array argument and loops over the array.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

I have created a new function which works with multiple parameters.

<?php
function parseQueryString($url,$remove_arr) {
    $infos=parse_url($url);
    $str=$infos["query"];
    $op = array();
    $pairs = explode("&", $str);
    foreach ($pairs as $pair) {
       list($k, $v) = array_map("urldecode", explode("=", $pair));
        $op[$k] = $v;
    }
    foreach($remove_arr as $remove){
        if(isset($op[$remove])){
            unset($op[$remove]);
        }
    }

    return str_replace($str,http_build_query($op),$url);

} 
echo parseQueryString("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],array("bar2","bar1"));
?>
ynh
  • 2,919
  • 1
  • 19
  • 18
0

I don't think the parseQueryString function will work for query strings with array components such as &bar[]=5&bar[]=12 etc. I think all but one would be dropped from the result.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • Welcome to StackOverflow and thanks for posting. Unfortunately, this doesn't really answer the question. Please have a look at [How to Answer](http://stackoverflow.com/questions/how-to-answer). – Serge Belov Nov 18 '12 at 21:41