Remove a value from a querystring Part 2

亡梦爱人 提交于 2019-12-11 07:34:06

问题


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


回答1:


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.




回答2:


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




回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/4238086/remove-a-value-from-a-querystring-part-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!