0

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
2
  • Can you elaborate on what you mean by it "fails"--does nothing happen at all, or it only trims out part of what it is supposed to? I'm suspecting that the $url variable is not actually URL-encoded yet, perhaps give the following a try: str_replace('area=' . $_GET['area'], '', $url); Commented Jul 13, 2022 at 0:03
  • @DashRantic question updated - nothing happens at all Commented Jul 13, 2022 at 0:05

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.