Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Last Part of URL PHP

Tags:

url

php

I'm just wondering how I can extract the last part of a URL using PHP.

The example URL is:

http://domain.com/artist/song/music-videos/song-title/9393903 

Now how can I extract the final part using PHP?

9393903 

There is always the same number of variables in the URL, and the id is always at the end.

like image 719
Belgin Fish Avatar asked Sep 12 '11 23:09

Belgin Fish


People also ask

How can I get the last part of a URL in PHP?

Split it apart and get the last element: $end = end(explode('/', $url)); # or: $end = array_slice(explode('/', $url), -1)[0];

How can get Uri segment in core PHP?

Get URI Segments in PHP Use the following code to get URL segments of the current URL. It returns all the segments of the current URL as an array. $uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

How to get the full URL in PHP?

To get the full URL in PHP – $full = (isset ($_SERVER ['HTTPS']) ? "https://" : "http://"). $_SERVER ['HTTP_HOST']. $_SERVER ['REQUEST_URI']; To remove the query string from the full URL – $full = strtok ($full, "?"); That should cover the basics, but if you need more specific “URL parts” – Read on for more examples!

What are the different parts of a URL?

The common parts of a URL are: Protocol – HTTP, HTTPS, FTP, or whatever else. Host – Better known as the “website address” to the non-technical folks. Port – Usually left out. But commonly understood to be 80 for HTTP, 443 for HTTPS, and 21 for FTP. Path – Beginners commonly mistake this to be the “folder”, but it’s really not. I.E.

How to get file name from URL without extension?

you can use basename ($url) function as suggested above. This returns the file name from the url. You can also provide the file extension as second argument to this function like basename ($url, '.jpg'), then the filename without the extension will be served.


1 Answers

The absolute simplest way to accomplish this, is with basename()

echo basename('http://domain.com/artist/song/music-videos/song-title/9393903'); 

Which will print

9393903

Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.

like image 114
nikc.org Avatar answered Sep 20 '22 13:09

nikc.org