php解析url并得到url中的参数及获取url参数的四种方式

发布时间:2026-02-23 20:32

如何在GitHub上克隆项目:复制项目的URL,打开Git Bash,输入`git clone ` #生活技巧# #数码产品使用技巧# #电脑操作教程#

https://www.jb51.net/article/73900.htm

下面通过四种实例给大家介绍php url 参数获取方式。

在已知URL参数的情况下,我们可以根据自身情况采用$_GET来获取相应的参数信息($_GET['name']);那,在未知情况下如何获取到URL上的参数信息呢?

第一种、利用$_SERVER内置数组变量

相对较为原始的$_SERVER['QUERY_STRING']来获取,URL的参数,通常使用这个变量返回的会是类似这样的数据:name=tank&sex=1
如果需要包含文件名的话可以使用$_SERVER["REQUEST_URI"](返回类似:/index.php?name=tank&sex=1)

第二种、利用pathinfo内置函数

 代码如下:

1

2

3

4

<?php

$test = pathinfo("http://localhost/index.php");

print_r($test);

/*

结果如下

1

2

3

4

5

6

7

8

9

Array

(

   [dirname] => http:

   [basename] => index.php

   [extension] => php

   [filename] => index

)

*/

?>

第三种、利用parse_url内置函数

代码如下:

1

2

3

4

<?php

$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");

print_r($test);

/*

结果如下

1

2

3

4

5

6

7

8

9

10

Array

(

   [scheme] => http

   [host] => localhost

   [path] => /index.php

   [query] => name=tank&sex=1

   [fragment] => top

)

*/

?>

第四种、利用basename内置函数

代码如下:

1

2

3

4

<?php

$test = basename("http://localhost/index.php?name=tank&sex=1#top");

echo $test;

/*

结果如下

1

2

3

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

*/

?>

另外,还有就是自己通过正则匹配的处理方式来获取需要的值了。这种方式较为精确,效率暂不考虑。。。
下面拓展实践下正则处理方式:

代码如下:

1

2

3

4

<?php

preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);

print_r($match);

/*

结果如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Array

(

  [0] => Array

    (

      [0] => name=tank

      [1] => sex=1#top

    )

  [1] => Array

     (

      [0] => name=tank

       [1] => sex=1

     )

   [2] => Array

    (

       [0] =>

      [1] => #top

    )

)

*/

?>

网址:php解析url并得到url中的参数及获取url参数的四种方式 https://c.klqsh.com/news/view/341765

相关内容

PHP中使用strpos函数高效检测字符串中是否包含特定字符的方法详解
Generate QR Code for URL for Free
错误:您所请求的网址(URL)无法获取
Python实战:高效爬取电影影评数据与文本分析技巧
如何利用python获取qq音乐榜单前的数据
使用Python爬取豆瓣电影影评:从数据收集到情感分析
如何获取web网页内容
Netease云音乐无损解析工具
基于反馈的电影评论数据分析
基于网络爬虫的电影评论爬取以及数据分析

随便看看