7

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.

1
  • I'm upping it for the regexes eat time comment... far too few people see that they are usually NOT the right tool for the job. Commented May 3, 2012 at 1:21

2 Answers 2

12
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

Sign up to request clarification or add additional context in comments.

7 Comments

Exactly what I would have suggested
@Alexander.Plutov I can't see anything wrong with this. It seems to work for me.
@symcbean I did not mean to suggest the answer had to have something to do with regexes, it is just that the answers I found on the web all used regexes and preg_replace. I much prefer the answers that don't.
@zod - don't worry, I guess he having mis-understanding on the question, no worry -2 only...
@zod. Yuo wrote remove the name value pair from the querystring. This code removes only value. n1=v1&n2=.
|
0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.