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.
Split it apart and get the last element: $end = end(explode('/', $url)); # or: $end = array_slice(explode('/', $url), -1)[0];
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));
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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With