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

(编辑:jimmy 日期: 2024/9/30 浏览:2)

下面一段代码是php解析url并得到url中的参数,代码如下所示:

<"color: #0000ff">第一种、利用$_SERVER内置数组变量

相对较为原始的$_SERVER['QUERY_STRING']来获取,URL的参数,通常使用这个变量返回的会是类似这样的数据:name=tank&sex=1
如果需要包含文件名的话可以使用$_SERVER["REQUEST_URI"](返回类似:/index.php"color: #0000ff">第二种、利用pathinfo内置函数

 代码如下:

<"http://localhost/index.php");
print_r($test);
/*

结果如下

Array
(
   [dirname] => http://localhost //url的路径
   [basename] => index.php //完整文件名
   [extension] => php //文件名后缀
   [filename] => index //文件名
)
*/
"color: #0000ff">第三种、利用parse_url内置函数

代码如下:

<"http://localhost/index.php");
print_r($test);
/*

结果如下

Array
(
   [scheme] => http //使用什么协议
   [host] => localhost //主机名
   [path] => /index.php //路径
   [query] => name=tank&sex=1 // 所传的参数
   [fragment] => top //后面根的锚点
)
*/
"color: #0000ff">第四种、利用basename内置函数

代码如下:

<"http://localhost/index.php");
echo $test;
/*

结果如下

index.php"htmlcode">
<"/(\w+=\w+)(#\w+)","http://localhost/index.php",$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
    )
)
*/
?>