如何获取 URL 中的最后一个路径?
我想获取 URL 中的最后一个路径段:
http://blabla/bla/wce/news.php
或http://blabla/blablabla/dut2a/news.php< /code>
例如,在这两个URL中,我想获取路径段:'wce'和'dut2a'。
我尝试使用 $_SERVER['REQUEST_URI']
,但我得到了整个 URL 路径。
I would like get the last path segment in a URL:
http://blabla/bla/wce/news.php
orhttp://blabla/blablabla/dut2a/news.php
For example, in these two URLs, I want to get the path segment: 'wce', and 'dut2a'.
I tried to use $_SERVER['REQUEST_URI']
, but I get the whole URL path.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
试试这个:
我还使用评论中的一些 URL 对其进行了测试。我必须假设所有路径都以斜杠结尾,因为我无法识别 /bob 是目录还是文件。这将假定它是一个文件,除非它也有尾部斜杠。
Try this:
I've also tested it with a few URLs from the comments. I'm going to have to assume that all paths end with a slash, because I can not identify if /bob is a directory or a file. This will assume it is a file unless it has a trailing slash too.
很容易
basename
将返回路径的尾随名称组件dirname
将返回父目录的路径http://php.net/manual/en/function.dirname.php
http://php.net/manual/en/function.basename.php
it is easy
basename
will return the trailing trailing name component of pathdirname
will return the parent directory's pathhttp://php.net/manual/en/function.dirname.php
http://php.net/manual/en/function.basename.php
试试这个:
Try this:
另一种解决方案:
1:获取最后一个斜杠位置
2:获取最后一个斜杠和字符串末尾之间的子字符串
看这里:TEST
Another solution:
1: getting the last slash position
2: getting the substring between the last slash and the end of string
Look here: TEST
如果你想处理绝对URL,那么你可以使用
parse_url()
(它不适用于相对网址)。完整代码示例:http://codepad.org/klqk5o29
If you want to process an absolute URL, then you can use
parse_url()
(it doesn't work with relative urls).Full code example here: http://codepad.org/klqk5o29
我自己写了一个小函数来获取 url 的最后一个目录/文件夹。它仅适用于真实/现有的网址,不适用于理论网址。就我而言,情况总是如此,所以......
对我有用!享受!并对之前的答案表示敬意!
I wrote myself a little function to get the last dir/folder of an url. It only works with real/existing urls, not theoretical ones. In my case, that was always the case, so ...
Works for me! Enjoy! And kudos to the previous answers!!!
这将保留最后一个斜杠之后的部分。
不用担心爆炸,例如当没有斜线时。
会给
This will keep the part after the last slash.
No worries about explode, when for example no slash is there.
Will give
尝试:
假设
$tokens
至少有 2 个元素。Try:
Assuming
$tokens
has at least 2 elements.