Get characters after last / in url


Question

I want to get the characters after the last / in an url like http://www.vimeo.com/1234567

How do I do with php?

1
112
5/6/2013 7:21:25 AM

Accepted Answer

Very simply:

$id = substr($url, strrpos($url, '/') + 1);

strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.


As mentioned by redanimalwar if there is no slash this doesn't work correctly since strrpos returns false. Here's a more robust version:

$pos = strrpos($url, '/');
$id = $pos === false ? $url : substr($url, $pos + 1);
232
11/2/2015 2:55:41 PM

$str = basename($url);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon