php 从 url 获取第二段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5455531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get second segment from url
提问by georgevich
How to get the second segment in URL without slashes ? For example I have a URL`s like this
如何在没有斜杠的情况下获取 URL 中的第二段?例如我有一个这样的网址
http://foobar/first/second
How to get the value where "first" stands ?
如何获得“第一”所在的价值?
回答by Gumbo
Use parse_url
to get the path from the URL and then use explode
to split it into its segments:
用于parse_url
从 URL 获取路径,然后用于explode
将其拆分为多个段:
$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'
回答by cloetensbrecht
$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
回答by Ravi Ram
To take your example http://domain.com/first/second
以你的例子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
您可以更改 numSegments -2 以获得第一个
回答by jamesnotjim
Here's my long-winded way of grabbing the last segment, inspired by Gumbo's answer:
这是我抓住最后一段的冗长方式,灵感来自 Gumbo 的回答:
// 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.
获得 后$currentSegment
,您可以将其回显或在 if/else 或 switch 语句中使用它,以根据最终段的值执行任何您喜欢的操作。