简体   繁体   English

从网址获取第二个细分

[英]Get second segment from url

How to get the second segment in URL without slashes ? 如何在没有斜杠的情况下获取URL中的第二个段? For example I have a URL`s like this 例如,我有一个像这样的URL

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: 使用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'
$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));

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以获得第一个

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语句中使用它,根据最终段的值执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM