php解析url的几种方式
1、利用$_SERVER内置数组变量
复制代码1
2
3
4
5
6
//URL的参数
echo $_SERVER['QUERY_STRING'];
返回:
m=admin&c=index&a=lists&catid=1&page=1
//包含文件名
echo $_SERVER["REQUEST_URI"];
登录后复制
返回:
复制代码1
/test.php?m=admin&c=index&a=lists&catid=1&page=1
登录后复制
2、利用pathinfo内置函数
复制代码1
2
3
echo "<pre>";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(pathinfo($url));
登录后复制
返回:
复制代码1
2
3
4
5
6
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',
)
登录后复制
3、利用parse_url内置函数
复制代码1
2
3
echo "<pre>";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(parse_url($url));
登录后复制
返回:
复制代码1
2
3
4
5
6
7
array (
'scheme' => 'http',
'host' => 'localhost',
'path' => '/test.php',
'query' => 'm=admin&c=index&a=lists&catid=1&page=1',
'fragment' => 'top',
)
登录后复制
4、利用basename内置函数
复制代码1
2
3
echo "<pre>";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(basename($url));
登录后复制
返回:
复制代码1
test.php?m=admin&c=index&a=lists&catid=1&page=1#top
登录后复制
5、正则匹配
复制代码1
2
3
4
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);
登录后复制
返回:
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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常用处理方法
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 将字符串参数变为数组
* @param $query
* @return array
*/
function convertUrlQuery($query)
{
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
/**
* 将参数变为字符串
* @param $array_query
* @return string
*/
function getUrlQuery($array_query)
{
$tmp = array();
foreach ($array_query as $k => $param) {
$tmp[] = $k . '=' . $param;
}
$params = implode('&', $tmp);
return $params;
}
登录后复制
例:
复制代码1
2
3
4
5
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);
登录后复制
返回:
复制代码1
2
3
4
5
6
7
array (
'm' => 'admin',
'c' => 'index',
'a' => 'lists',
'catid' => '1',
'page' => '1',
)
登录后复制
复制代码1
var_export(getUrlQuery($arr_query));
登录后复制
返回:
复制代码1
m=admin&c=index&a=lists&catid=1&page=1
登录后复制
相关教程推荐:《PHP教程》
以上就是php如何解析url?解析url的5种方式介绍的详细内容,更多请关注靠谱客其它相关文章!
最后
以上就是等待彩虹最近收集整理的关于php如何解析url?解析url的5种方式介绍的全部内容,更多相关php如何解析url?解析url内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复