解析url的3个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.<?php
2.$test = pathinfo("http://localhost/index.php");
3.print_r($test);
4.?>
5.结果如下
6.Array
7.(
8. => http://localhost //url的路径
9. => index.php //完整文件名
10. => php //文件名后缀
11. => index //文件名
12.)
<?php
$test = pathinfo("http://localhost/index.php");
print_r($test);
?>
结果如下
Array
(
=> http://localhost //url的路径
=> index.php //完整文件名
=> php //文件名后缀
=> index //文件名
)2,利用parse_url
1.<?php
2.$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");
3.print_r($test);
4.?>
5.结果如下
6.Array
7.(
8. => http //使用什么协议
9. => localhost //主机名
10. => /index.php //路径
11. => name=tank&sex=1 // 所传的参数
12. => top //后面根的锚点
13.)
<?php
$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");
print_r($test);
?>
结果如下
Array
(
=> http //使用什么协议
=> localhost //主机名
=> /index.php //路径
=> name=tank&sex=1 // 所传的参数
=> top //后面根的锚点
)3,利用basename
1.<?php
2.$test = basename("http://localhost/index.php?name=tank&sex=1#top");
3.echo $test;
4.?>
5.结果如下
6.index.php?name=tank&sex=1#top
<?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.<?php
2.preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);
3.print_r($match);?>
4.结果如下
5.Array
6.(
7. => Array
8. (
9. => name=tank
10. => sex=1#top
11. )
12. => Array
13. (
14. => name=tank
15. => sex=1
16. )
17. => Array
18. (
19. =>
20. => #top
21. )
22.)
<?php
preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);
print_r($match);?>
结果如下
Array
(
=> Array
(
=> name=tank
=> sex=1#top
)
=> Array
(
=> name=tank
=> sex=1
)
=> Array
(
=>
=> #top
)
)要的数据都匹配出来了,好长时间搞正则了,手都有点生了。上面正则中的规则不是死的,规则是根据url来推测的。
页:
[1]