Extracting Last URL Component with PHP
To obtain the final component of a URL using PHP, consider the following approaches:
1. Utilizing basename():
The basename() function provides an effortless method for extracting the final portion of a URL.
echo basename('http://domain.example/artist/song/music-videos/song-title/9393903');
This method will output:
9393903
However, it's worth noting that if the URL contains a query string, it will be included in the extracted value.
2. Preferred Method:
For more precise control and to exclude potential query strings, consider the following approach:
$url = 'http://domain.example/artist/song/music-videos/song-title/9393903'; $parts = parse_url($url); echo end($parts['path']);
This method will accurately extract the final component:
9393903
By employing this preferred method, you can effectively extract the last part of a URL in PHP, regardless of the presence of a query string.
The above is the detailed content of How to Extract the Last URL Component in PHP?. For more information, please follow other related articles on the PHP Chinese website!