Home > Backend Development > PHP Tutorial > How to Extract the Last URL Component in PHP?

How to Extract the Last URL Component in PHP?

Susan Sarandon
Release: 2024-12-15 08:51:16
Original
172 people have browsed it

How to Extract the Last URL Component in PHP?

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

This method will output:

9393903
Copy after login
Copy after login

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

This method will accurately extract the final component:

9393903
Copy after login
Copy after login

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!

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