I have a string with a full URL including GET variables. Which is the best way to remove the GET variables? Is there a nice way to remove just one of them?
This is a code that works but is not very beautiful (I think):
$current_url = explode('?', $current_url);
echo $current_url[0];
The code above just removes all the GET variables. The URL is in my case generated from a CMS so I don't need any information about server variables.
Inspired by the comment of @MitMaro, I wrote a small benchmark to test the speed of solutions of @Gumbo, @Matt Bridges and @justin the proposal in the question:
Result: @justin's strtok is the fastest.
Note: tested on a local Debian Lenny system with Apache2 and PHP5.
If the URL that you are trying to remove the query string from is the current URL of the PHP script, you can use one of the previously mentioned methods. If you just have a string variable with a URL in it and you want to strip off everything past the '?' you can do:
Ok, to remove all variables, maybe the prettiest is
See about
strtok
here.Its the fastest (see below), and handles urls without a '?' properly.
To take a url+querystring and remove just one variable (without using a regex replace, which may be faster in some cases), you might do something like:
A regex replace to remove a single var might look like:
Heres the timings of a few different methods, ensuring timing is reset inbetween runs.
shows
strtok wins, and is by far the smallest code.
You can use the server variables for this, for example
$_SERVER['REQUEST_URI']
, or even better:$_SERVER['PHP_SELF']
.