How do I remove a certain variable from a query string? Say I have a query string
$query_string = "first=val1&second=val2&third=val3";
function removevar($var, $query_string) {
return preg_replace("/(".$var."=[^&]*(&))/i","",$query_string);
}
echo removevar("first",$query_string); // ok
echo removevar("second",$query_string); // ok
echo removevar("third",$query_string); // doesn't change the string because third doesn't have a trailing &
How can this be fixed so that it removes variables from a query string in a robust way? Probably someone already has a function that does this along with special cases in more complex strings.
So I'd have to match either & or end of the string ($) but I don't know how to turn that into regex.
$query_string = "first=val1&second=val2&third=val3";
function removevar($var, $query_string) {
return preg_replace("/(".$var."=[^&]*(&|$))/i","",$query_string);
}
echo removevar("first",$query_string); // ok
echo removevar("second",$query_string); // ok
echo removevar("third",$query_string); // ok
This should do the trick.
You don’t necessarily need regular expressions for this as PHP does have functions that can parse and build query strings (parse_str and http_build_query respectively):
function removevar($var, $query_string) {
parse_str($query_string, $args);
unset($args[$var]);
return http_build_query($args);
}
Note that you need to decode the HTML character references before using these functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With