Grab remaining text after last “/” in a php string

前端 未结 8 1970
我寻月下人不归
我寻月下人不归 2020-12-28 11:47

So, lets say I have a $somestring thats holds the value \"main/physician/physician_view\".

I want to grab just \"physician_view\". I want it to also wo

相关标签:
8条回答
  • 2020-12-28 12:25

    You can use strrpos() to find the last occurence of one string in another:

    substr($somestring, strrpos($somestring, '/') + 1)
    
    0 讨论(0)
  • 2020-12-28 12:27
    $last_part = substr(strrchr($somestring, "/"), 1);
    

    Examples:

    php > $a = "main/physician/physician_view";
    php > $b = "main/physician_view";
    php > $c = "site/main/physician/physician_view";
    php > echo substr(strrchr($a, "/"), 1);
        physician_view
    php > echo substr(strrchr($b, "/"), 1);
        physician_view
    php > echo substr(strrchr($c, "/"), 1);
        physician_view
    
    0 讨论(0)
  • 2020-12-28 12:29

    For another one liner, you can use the explode trick and reverse the array:

    current(array_reverse(explode('/',$url)));
    
    0 讨论(0)
  • 2020-12-28 12:29

    Simply you can use :

    $id = substr( $url, strrpos( $url, '/' )+1 );
    
    0 讨论(0)
  • 2020-12-28 12:31

    There are many ways to do this. I would probably use:

    array_pop(explode('/', $string));
    
    0 讨论(0)
  • 2020-12-28 12:37

    The other solutions don't always work, or are inefficient. Here is a more useful general utility function that always works, and can be used with other search terms.

    /**
     * Get a substring starting from the last occurrence of a character/string
     *
     * @param  string $str The subject string
     * @param  string $last Search the subject for this string, and start the substring after the last occurrence of it.
     * @return string A substring from the last occurrence of $startAfter, to the end of the subject string.  If $startAfter is not present in the subject, the subject is returned whole.
     */
    function substrAfter($str, $last) {
        $startPos = strrpos($str, $last);
        if ($startPos !== false) {
            $startPos++;
            return ($startPos < strlen($str)) ? substr($str, $startPos) : '';
        }
        return $str;
    }
    
    
    // Examples
    
    substrAfter('main/physician/physician_view', '/');  // 'physician_view'
    
    substrAfter('main/physician/physician_view/', '/'); // '' (empty string)
    
    substrAfter('main_physician_physician_view', '/');  // 'main_physician_physician_view'
    
    0 讨论(0)
提交回复
热议问题