简体   繁体   中英

PHP function to remove key from a query string

I have a query string, like:

n1=v1&n2=v2&n3=v3

etc

I just want a php function that will accept the query string and the name (key), and remove the name value pair from the querystring.

Every example I have found uses regexes and assumes that the value will exist and that it will not be empty, but in my case (and possibly in general, I would like to know) this would also be a valid query:

n1=v1&n2=&n3

I don't know in advance how many keys there will be.

I am convinced that regexes are monsters that eat time. Eventually all matter in the universe will end up in a regex.

parse_str('n1=v1&n2=&n3', $gets);
unset($gets['n3']);
echo http_build_query($gets);

NOTE: unset($gets['n3']); is just a show-case example

function stripkey($input, $key) {

$parts= explode("&", $input); foreach($parts as $k=>$part) { if(strpos($part, "=") !== false) { $parts2= explode("=", $part); if($key == $parts2[0]){ unset($parts[$k]); } } } return join("&", $parts);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM