Home >Backend Development >PHP Tutorial >How Can I Remove Query Strings from URLs in PHP to Get Clean URLs?
In PHP, URLs often include querystrings that contain additional information. However, sometimes you may need to retrieve only the clean URL without the querystring.
To accomplish this, you can employ the strtok() function:
$url = strtok($_SERVER["REQUEST_URI"], '?');
strtok() efficiently captures the string before the first occurrence of the ?.
While strtok() is the recommended approach, there are alternative techniques:
To illustrate the different techniques, consider the following URLs:
The output of the different methods is as follows:
Method | Output |
---|---|
strtok() | www.example.com/myurl.html |
strstr(/true) | www.example.com/myurl.html |
explode(/2) | www.example.com/myurl.html |
substr/strrpos() | www.example.com/myurl.html |
As you can see, strtok() consistently provides the correct result, while the other techniques may fail in certain cases, especially when the querystring is missing.
The above is the detailed content of How Can I Remove Query Strings from URLs in PHP to Get Clean URLs?. For more information, please follow other related articles on the PHP Chinese website!