user1444027
user1444027

Reputation: 5251

Remove one querystring parameter from a URL with multiple querystring parameters

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%2C+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%2C+People%27s+Republic+of+China&fruit=bananas

The %27 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%2C+Taiwan&fruit=bananas

Upvotes: 0

Views: 163

Answers (2)

Tyler Dill
Tyler Dill

Reputation: 371

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%2C+People%27s+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;

Upvotes: 1

DashRantic
DashRantic

Reputation: 1518

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.

Upvotes: 0

Related Questions