Get second segment from url

前端 未结 4 929
悲&欢浪女
悲&欢浪女 2020-12-25 11:53

How to get the second segment in URL without slashes ? For example I have a URL`s like this

http://foobar/first/second

How to get the valu

相关标签:
4条回答
  • 2020-12-25 12:37

    To take your example http://domain.com/first/second

    $segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
    $numSegments = count($segments); 
    $currentSegment = $segments[$numSegments - 1];
    
    echo 'Current Segment: ' , $currentSegment;
    

    Would result in Current Segment: second

    You can change the numSegments -2 to get first

    0 讨论(0)
  • 2020-12-25 12:40
    $segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
    
    0 讨论(0)
  • 2020-12-25 12:51

    Here's my long-winded way of grabbing the last segment, inspired by Gumbo's answer:

    // finds the last URL segment  
    $urlArray = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $segments = explode('/', $urlArray);
    $numSegments = count($segments); 
    $currentSegment = $segments[$numSegments - 1];
    

    You could boil that down into two lines, if you like, but this way makes it pretty obvious what you're up to, even without the comment.

    Once you have the $currentSegment, you can echo it out or use it in an if/else or switch statement to do whatever you like based on the value of the final segment.

    0 讨论(0)
  • 2020-12-25 12:55

    Use parse_url to get the path from the URL and then use explode to split it into its segments:

    $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $uri_segments = explode('/', $uri_path);
    
    echo $uri_segments[0]; // for www.example.com/user/account you will get 'user'
    
    0 讨论(0)
提交回复
热议问题