开发者

Remove a value from a querystring Part 2

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'] . $_SE开发者_StackOverflow中文版RVER['REQUEST_URI'],"bar2","bar1");

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

Any help appreciated.

Thank you,

Matt


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


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.


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"));
?>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜