views:

295

answers:

6

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

How do I do with php?

A: 

You could explode() based on "/" and get the last entry.

print end(explode("/", "http://www.vimeo.com/1234567"));
Jonathan Sampson
`explode` always seems like more overhead to me, though I haven't ever timed it to see how fast it is.
DisgruntledGoat
It appears explode() is a bit slower. On 10k instances, this is the amount of time taken for both. substr() first: 0.013657/0.045038
Jonathan Sampson
+5  A: 

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.

DisgruntledGoat
+1  A: 

array_pop(explode("/", "http://vimeo.com/1234567")); will return the last element of the example url

nikc
A: 
$str = "http://www.vimeo.com/1234567";
$s = explode("/",$str);
print end($s);
ghostdog74
This solution was provided 15 minutes earlier :)
Jonathan Sampson
my version, although the end result is the same as the one posted, enables OP to use the other items of the split up string if he wished to.
ghostdog74
+1  A: 

You can use substr and strrchr:

$url = 'http://www.vimeo.com/1234567';
$str = substr(strrchr($url, '/'), 1);
echo $str;      // Output: 1234567
Gabriel
A: 
$str = basename($url);
GZipp