Remove a value from a querystring

走远了吗. 提交于 2019-12-13 03:41:54

问题


I have a URL in which a querystring is produced by a PHP script. Various values are displayed in the querystring.

Basically, I need to remove a specific value from the query string when a visitor clicks on a link or a 'remove' button.

So, the querystring looks like this:

http://www.foo.com/script.php?bar1=green&bar2=blue

But when a link or 'remove' button is clicked by a user, bar1=green is removed, and the visitor is directed to the following URL:

http://www.foo.com/script.php?bar2=blue

I thought this would be easy using basic HTML with a form or anchor but I haven't been able to do it so far.

Just so you know, i do not have access to the code on the PHP script itself; it is hosted remotely and is called to my webpage by a PHP wrapper using an iframe.

Any suggestions greatly appreciated.

Many thanks,

Matt


回答1:


You can remove the value from the query string using this code:

<?php
function parseQueryString($url,$remove) {
    $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;
    }
    if(isset($op[$remove])){
        unset($op[$remove]);
    }

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

} 
echo parseQueryString( "http://www.foo.com/script.php?bar1=green&bar2=blue","bar2");
?>



回答2:


Check out How can I get query string values in JavaScript?.



来源:https://stackoverflow.com/questions/4233636/remove-a-value-from-a-querystring

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