How to Extract the Last Segment of a URL in PHP?

Susan Sarandon
Release: 2024-11-11 22:53:03
Original
834 people have browsed it

How to Extract the Last Segment of a URL in PHP?

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');
Copy after login

This will yield the expected output:

9393903
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template