Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a certain variable from a query string

Tags:

regex

php

pcre

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.

like image 293
A-OK Avatar asked Nov 28 '25 09:11

A-OK


2 Answers

$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.

like image 166
buschtoens Avatar answered Nov 30 '25 00:11

buschtoens


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.

like image 25
Gumbo Avatar answered Nov 29 '25 23:11

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!