Get characters after last / in url

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

How do I do with php?

+80
string php
Sep 01 '09 at 10:40
source share
8 answers

Very simple:

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

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




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

 $pos = strrpos($url, '/'); $id = $pos === false ? $url : substr($url, $pos + 1); 
+174
Sep 01 '09 at 10:43
source share
 $str = basename($url); 
+27
01 Sep '09 at 13:30
source share

You can explode based on "/" and return the last entry:

 print end( explode( "/", "http://www.vimeo.com/1234567" ) ); 

This is based on line swelling, something that is not necessary if you know that the structure of the line itself will not change soon. You can also use regex to define this value at the end of a line:

 $url = "http://www.vimeo.com/1234567"; if ( preg_match( "/\d+$/", $url, $matches ) ) { print $matches[0]; } 
+12
Sep 01 '09 at 10:41
source share

You can use substr and strrchr :

 $url = 'http://www.vimeo.com/1234567'; $str = substr(strrchr($url, '/'), 1); echo $str; // Output: 1234567 
+9
Sep 01 '09 at 11:58
source share
 $str = "http://www.vimeo.com/1234567"; $s = explode("/",$str); print end($s); 
+4
Sep 01 '09 at 10:55
source share

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

+1
Sep 01 '09 at 10:46
source share

Two single liners - I suspect that the first one is faster, but the second one is prettier and unlike end() and array_pop() , you can pass the result of the function directly to current() without creating any notifications or warnings, since does not move the pointer or does not change the array.

 $var = 'http://www.vimeo.com/1234567'; // VERSION 1 - one liner simmilar to DisgruntledGoat answer above echo substr($a,(strrpos($var,'/') !== false ? strrpos($var,'/') + 1 : 0)); // VERSION 2 - explode, reverse the array, get the first index. echo current(array_reverse(explode('/',$var))); 
0
Jan 10 '17 at 14:35
source share

Here is a beautiful dynamic function that I wrote to remove the last part of a URL or path.

 /** * remove the last directories * * @param $path the path * @param $level number of directories to remove * * @return string */ private function removeLastDir($path, $level) { if(is_int($level) && $level > 0){ $path = preg_replace('#\/[^/]*$#', '', $path); return $this->removeLastDir($path, (int) $level - 1); } return $path; } 
-one
May 27 '15 at 12:34
source share



All Articles