Get characters after last / in url

后端 未结 8 880
梦谈多话
梦谈多话 2020-11-30 20:05

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

How do I do with php?

相关标签:
8条回答
  • 2020-11-30 20:13

    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);
    
    0 讨论(0)
  • 2020-11-30 20:13
    $str = basename($url);
    
    0 讨论(0)
  • 2020-11-30 20:22

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

    0 讨论(0)
  • 2020-11-30 20:23
    $str = "http://www.vimeo.com/1234567";
    $s = explode("/",$str);
    print end($s);
    
    0 讨论(0)
  • 2020-11-30 20:25

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

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

    That's based on blowing the string apart, something that isn't necessary if you know the pattern of the string itself will not soon be changing. You could, alternatively, use a regular expression to locate that value at the end of the string:

    $url = "http://www.vimeo.com/1234567";
    
    if ( preg_match( "/\d+$/", $url, $matches ) ) {
        print $matches[0];
    }
    
    0 讨论(0)
  • 2020-11-30 20:30

    Two one liners - I suspect the first one is faster but second one is prettier and unlike end() and array_pop(), you can pass the result of a function directly to current() without generating any notice or warning since it doesn't move the pointer or alter the array.

    $var = 'http://www.vimeo.com/1234567';
    
    // VERSION 1 - one liner simmilar to DisgruntledGoat's 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 讨论(0)
提交回复
热议问题