3个解析url的php函数

通过url进行传值,是php中一个传值的重要手段。所以我们要经常对url里面所带的参数进行解析,如果我们知道了url传递参数名称,例如

/index.php?name=tank&sex=1#top

我们就可以通过$_GET['name']$_GET['sex']来获得传的数据。但是如果我们不知道这些变量名又怎么办呢?这也是写这篇博文的目的,因为自己老是忘,所以做个标记,下次就不要到处找了。

我们可以通php的变量来获得url和要传的参数字符串

$_SERVER["QUERY_STRING"] name=tank&sex=1

$_SERVER["REQUEST_URI"] /index.php?name=tank&sex=1

javascript也可以获得来源的url,document.referrer;方法有很多。

1,利用pathinfo

1
2
3
4
5
6
7
8
9
10
11
12
<?php    
$test = pathinfo("http://localhost/index.php");
print_r($test);
?>
结果如下
Array
(
[dirname] => http://localhost //url的路径
[basename] => index.php //完整文件名
[extension] => php //文件名后缀
[filename] => index //文件名
)

2,利用parse_url

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php    
$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");
print_r($test);
?>
结果如下
Array
(
[scheme] => http //使用什么协议
[host] => localhost //主机名
[path] => /index.php //路径
[query] => name=tank&sex=1 // 所传的参数
[fragment] => top //后面根的锚点
)

3,利用basename

1
2
3
4
5
6
<?php    
$test = basename("http://localhost/index.php?name=tank&sex=1#top");
echo $test;
?>
结果如下
index.php?name=tank&sex=1#top

上面三种方法,我们基本上,就可以得我们所要的东西了。其实还有一种方法就是用正则,也可以很快的得到我们想到的数据。

传递的参数方式有很多,但是主要有这二种,一种是,name=tank&sex=1#top;一种是,name=tank&sex=1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php  
preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);
print_r($match);
?>
结果如下
Array
(
[0] => Array
(
[0] => name=tank
[1] => sex=1#top
)
[1] => Array
(
[0] => name=tank
[1] => sex=1
)
[2] => Array
(
[0] =>
[1] => #top
)
)
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
<?php    
preg_match_all("/(\w+)=(\w+)/i","http://localhost/index.php?name=tank&sex=1",$match);
print_r($match);
?>
结果如下
Array
(
[0] => Array
(
[0] => name=tank
[1] => sex=1
)

[1] => Array
(
[0] => name
[1] => sex
)

[2] => Array
(
[0] => tank
[1] => 1
)

)

要的数据都匹配出来了,好长时间搞正则了,手都有点生了。上面正则中的规则不是死的,规则是根据url来推测的。