Get second segment from url
How to get the second segment in URL without开发者_StackOverflow slashes ? For example I have a URL`s like this
http://foobar/first/second
How to get the value where "first" stands ?
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'
$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
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
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.
精彩评论