php解析url几种方式
- 利用$_SERVER内置数组变量
访问:
http:
echo $_SERVER['QUERY_STRING'];
返回:
m=admin&c=index&a=lists&catid=1&page=1
echo $_SERVER["REQUEST_URI"];
返回:
/test.php?m=admin&c=index&a=lists&catid=1&page=1
- 利用pathinfo内置函数
echo "<pre>";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(pathinfo($url));
返回:
array (
'dirname' => 'http://localhost',
'basename' => 'test.php?m=admin&c=index&a=lists&catid=1&page=1#top',
'extension' => 'php?m=admin&c=index&a=lists&catid=1&page=1#top',
'filename' => 'test',
)
- 利用parse_url内置函数
echo "<pre>";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(parse_url($url));
返回:
array (
'scheme' => 'http',
'host' => 'localhost',
'path' => '/test.php',
'query' => 'm=admin&c=index&a=lists&catid=1&page=1',
'fragment' => 'top',
)
- 利用basename内置函数
echo "<pre>";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(basename($url));
返回:
test.php?m=admin&c=index&a=lists&catid=1&page=1
- 正则匹配
echo "<pre>";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
preg_match_all("/(\w+=\w+)(#\w+)?/i",$url,$match);
var_export($match);
返回:
array (
0 =>
array (
0 => 'm=admin',
1 => 'c=index',
2 => 'a=lists',
3 => 'catid=1',
4 => 'page=1#top',
),
1 =>
array (
0 => 'm=admin',
1 => 'c=index',
2 => 'a=lists',
3 => 'catid=1',
4 => 'page=1',
),
2 =>
array (
0 => '',
1 => '',
2 => '',
3 => '',
4 => '#top',
),
)
url常用处理方法
function convertUrlQuery($query)
{
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
function getUrlQuery($array_query)
{
$tmp = array();
foreach ($array_query as $k => $param) {
$tmp[] = $k . '=' . $param;
}
$params = implode('&', $tmp);
return $params;
}
例:
echo "<pre>";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
$arr = parse_url($url);
$arr_query = convertUrlQuery($arr['query']);
var_export($arr_query);
返回:
array (
'm' => 'admin',
'c' => 'index',
'a' => 'lists',
'catid' => '1',
'page' => '1',
)
var_export(getUrlQuery($arr_query));
返回:
m=admin&c=index&a=lists&catid=1&page=1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?