I've been using the following function to remove a get parameter for a long time:
function removeGetParameter($url, $varname) {
return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}
(taken from this thread)
But I have noticed that if I remove all parameters, I'll get a question mark suffix ?
at the end of the string. I can't just trim the ?
off if found at the end of the string, as it might be the value of another GET parameter (i.e http://example.com?myquestion=are+you+here?
).
I came up with this solution, but I doubt its efficiency.
function removeGetParameter($url, $varname) {
$p = parse_url($url);
parse_str($p['query'], $vars);
unset($vars[$varname]);
$vars_str = (count($vars) ? '?':'').http_build_query($vars);
return $p['scheme'].'://'.$p['host'].$vars_str;
}
It gets the job done, but I believe it is slower than many other options.
Is there any common, safe method to remove a specific GET parameter from a given URL?
Thanks!
Edit: I added that if
condifion to be safer (we might have no variables at all)
function removeGetParameter($url, $varname) {
$p = parse_url($url); // parse the url to parts.
$final = $p['scheme'].'://'.$p['host']; // build the url from the protocol and host.
if(!empty($p['query'])) { // if we have any get parameters
parse_str($p['query'], $vars); // make an array of them ($vars)
unset($vars[$varname]); // unset the wanted
$vars_str = (count($vars) ? '?':'').http_build_query($vars); // if has any variables, add a question mark
return $final.$vars_str; // merge all together
} else {
return $final; // no variables needed.
}
}
Is this the optimal solution?