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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:29:53  来源:igfitidea点击:

Get second segment from url

php

提问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_urlto get the path from the URL and then use explodeto 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 语句中使用它,以根据最终段的值执行任何您喜欢的操作。