• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-25) 45次浏览 已收录 0个评论

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

 string 'content' (length=7)          'c' => string 'index' (length=5)          'a' => string 'lists' (length=5)          'catid' => string '6' (length=1)          'area' => string '0' (length=1)          'author' => string '0' (length=1)          'h' => string '0' (length=1)          'region' => string '0' (length=1)          's' => string '1' (length=1)          'page' => string '1' (length=1) */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 string 'm=content&c=index&a=lists&catid=6&area=0&author=0&h=0&region=0&s=1&page=1' (length=73) */function getUrlQuery($array_query){  $tmp = array();  foreach($array_query as $k=>$param)  {    $tmp[] = $k.'='.$param;  }  $params = implode('&',$tmp);  return $params;}

下面通过四种实例给大家介绍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内置函数

代码如下:

<?php$test =<em>/本2文来源[email protected]搞@^&代*@码2网</em><strong>搞gaodaima代码</strong> pathinfo("http://localhost/index.php");print_r($test);/*

结果如下

Array(   [dirname] => http://localhost //url的路径   [basename] => index.php //完整文件名   [extension] => php //文件名后缀   [filename] => index //文件名)*/?>

第三种、利用parse_url内置函数

代码如下:

<?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 //后面根的锚点)*/?>

第四种、利用basename内置函数

代码如下:

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

结果如下

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

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

代码如下:

<?phppreg_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    ))*/?>

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php解析url并得到url中的参数及获取url参数的四种方式_php实例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址