Retrieving the Final Element of a URL in PHP
Determining how to isolate the final portion of a given URL can arise as a common programming requirement. PHP provides several robust mechanisms to achieve this objective.
Solution 1: Employing basename()
One straightforward approach is utilizing the basename() function, which conveniently extracts the final element of a URL path:
echo basename('http://example.com/artist/song/music-videos/song-title/9393903');
This will yield the expected output:
9393903
Solution 2: Leveraging parse_url() and pathinfo()
For more nuanced URL parsing requirements, consider implementing the parse_url() and pathinfo() functions in tandem:
$parsedUrl = parse_url('http://example.com/artist/song/music-videos/song-title/9393903'); $id = pathinfo($parsedUrl['path'], PATHINFO_BASENAME); echo $id;
Further Considerations
Whichever solution you select, bear in mind that if the URL includes a query string, it will be incorporated into the returned value. In such instances, additional processing may be necessary to isolate the desired id.
The above is the detailed content of How to Extract the Last Segment of a URL in PHP?. For more information, please follow other related articles on the PHP Chinese website!