Home > OS >  Remove one querystring parameter from a URL with multiple querystring parameters
Remove one querystring parameter from a URL with multiple querystring parameters

Time:07-13

I would like to remove a querystring parameter from a url that may contain multiple. I have succeeded in doing this using str_replace so far like this:

$area_querystring = urlencode($_GET['area']);
str_replace('area=' . $area_querystring, '', $url);

preg_replace also works, like this:

preg_replace('~(\?|&)area=[^&]*~', '$1', $url)

Either works fine for most URLs. For example:

http://localhost:8000/country/tw/?area=Taipei, Taiwan&fruit=bananas

Becomes:

http://localhost:8000/country/tw/?&fruit=bananas

However, if the querystring contains an apostrophe html entity, nothing happens at all. E.g.:

http://localhost:8000/country/cn/?area=Shanghai, People's Republic of China&fruit=bananas

The ' part of the url (an apostrophe) seems to be the cause.

To be clear, I don't wish to remove all of the URL after the last /, just the area querystring portion (the fruit=bananas part of the url should remain). Also, the area parameter does not always appear in the same place in the URL, sometimes it may appear after other querystring parameters e.g.

http://localhost:8000/country/tw/?lang=taiwanese&area=Taipei, Taiwan&fruit=bananas

CodePudding user response:

You can use the GET array and filter out the area key. Then rebuild the url with http_build_query. Like this:

$url = 'http://localhost:8000/country/cn/?area=Shanghai, People's Republic of China&fruit=bananas';
$filtered = array_filter($_GET, function ($key) {
    return $key !== 'area';
}, ARRAY_FILTER_USE_KEY);
$parsed = parse_url($url);
$query = http_build_query($filtered);
$result = $parsed['scheme'] . "://" . $parsed['host'] . $parsed['path'] . "?" . $query;

CodePudding user response:

You probably don't need urlencode() -- I'm guessing your $url variable is not yet encoded, so if there are any characters like an apostrophe, there won't be a match.

So:

$area_querystring = $_GET['area'];

should do the trick! No URL encoding/decoding needed.

  • Related