【发布时间】:2011-10-22 13:34:43
【问题描述】:
我只是想知道使用 PHP 从 URL 中提取“参数”的最佳方法是什么。
如果我得到了网址:
http://example.com/user/100
如何使用 PHP 获取用户 ID (100)?
【问题讨论】:
我只是想知道使用 PHP 从 URL 中提取“参数”的最佳方法是什么。
如果我得到了网址:
http://example.com/user/100
如何使用 PHP 获取用户 ID (100)?
【问题讨论】:
为了彻底,您需要从 parse_url() 开始。
$parts=parse_url("http://example.com/user/100");
这将为您提供一个包含少量键的数组。你要找的是path。
在/ 上分割路径并取最后一条。
$path_parts=explode('/', $parts['path']);
您的 ID 现在在 $path_parts[count($path_parts)-1]。
【讨论】:
$url = "http://example.com/user/100";
$parts = Explode('/', $url);
$id = $parts[count($parts) - 1];
【讨论】:
你可以使用parse_url(),即:
$parts = parse_url("http://x.com/user/100");
$path_parts= explode('/', $parts[path]);
$user = $path_parts[2];
echo $user;
# 100
parse_url()
此函数解析一个 URL 并返回一个关联数组,其中包含 存在的 URL 的任何各种组件。价值 的数组元素未进行 URL 解码。
此函数并非用于验证给定的 URL,它只会破坏它 到上面列出的部分。部分 URL 也是 接受后,parse_url() 会尽力正确解析它们。
【讨论】:
我知道这是一个旧线程,但我认为以下是更好的答案:
basename(dirname(__FILE__))
【讨论】: