Get last word from URL after a slash in PHP

后端 未结 8 1975
囚心锁ツ
囚心锁ツ 2020-12-06 00:50

I need to get the very last word from an URL. So for example I have the following URL:

http://www.mydomainname.com/m/groups/view/test

I need to get with PHP

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 01:07

    You can use explode but you need to use / as delimiter:

    $segments = explode('/', $_SERVER['REQUEST_URI']);
    

    Note that $_SERVER['REQUEST_URI'] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:

    $_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    

    And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:

    $_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $segments = explode('/', rtrim($_SERVER['REQUEST_URI_PATH'], '/'));
    

提交回复
热议问题