Get last word from URL after a slash in PHP

后端 未结 8 1969
囚心锁ツ
囚心锁ツ 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:03

    To do that you can use explode on your REQUEST_URI.I've made some simple function:

    function getLast()
    {
        $requestUri = $_SERVER['REQUEST_URI'];
    
       # Remove query string
        $requestUri = trim(strstr($requestUri, '?', true), '/');
       # Note that delimeter is '/'
        $arr = explode('/', $requestUri);
        $count = count($arr);
    
        return $arr[$count - 1];
    }
    
    echo getLast();
    
    0 讨论(0)
  • 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'], '/'));
    
    0 讨论(0)
  • 2020-12-06 01:11

    If you don't mind a query string being included when present, then just use basename. You don't need to use parse_url as well.

    $url = 'http://www.mydomainname.com/m/groups/view/test';
    $showword = basename($url);
    echo htmlspecialchars($showword);
    

    When the $url variable is generated from user input or from $_SERVER['REQUEST_URI']; before using echo use htmlspecialchars or htmlentities, otherwise users could add html tags or run JavaScript on the webpage.

    0 讨论(0)
  • 2020-12-06 01:13

    Use basename with parse_url:

    echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
    
    0 讨论(0)
  • 2020-12-06 01:16
    ex: $url      = 'http://www.youtube.com/embed/ADU0QnQ4eDs';
    $url      = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $url_path = parse_url($url, PHP_URL_PATH);
    $basename = pathinfo($url_path, PATHINFO_BASENAME);
    // **output**: $basename is "ADU0QnQ4eDs"
    

    complete solution you will get in the below link. i just found to Get last word from URL after a slash in PHP.

    Get last parameter of url in php

    0 讨论(0)
  • 2020-12-06 01:21

    use preg*

    if ( preg_match( "~/(.*?)$~msi", $_SERVER[ "REQUEST_URI" ], $vv ))
     echo $vv[1];
    else
     echo "Nothing here";
    

    this was just idea of code. It can be rewriten in function.

    PS. Generally i use mod_rewrite to handle this... ans process in php the $_GET variables. And this is good practice, IMHO

    0 讨论(0)
提交回复
热议问题