Get second segment from url

前端 未结 4 961
悲&欢浪女
悲&欢浪女 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: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.

提交回复
热议问题