PHP解析url的几种方式
1、利用$_SERVER内置数组变量
访问:
http://localhost/test.PHP?m=admin&c=index&a=Lists&catID=1&page=1
//URL的参数echo $_SERVER['query_STRING'];返回:m=admin&c=index&a=Lists&catID=1&page=1//包含文件名echo $_SERVER["REQUEST_URI"];
返回:
/test.PHP?m=admin&c=index&a=Lists&catID=1&page=1
2、利用pathinfo内置函数
echo "<pre>";$url = 'http://localhost/test.PHP?m=admin&c=index&a=Lists&catID=1&page=1#top';var_export(pathinfo($url));
返回:
array ( 'dirname' => 'http://localhost', 'basename' => 'test.PHP?m=admin&c=index&a=Lists&catID=1&page=1#top', 'extension' => 'PHP?m=admin&c=index&a=Lists&catID=1&page=1#top', 'filename' => 'test',)
3、利用parse_url内置函数
echo "<pre>";$url = 'http://localhost/test.PHP?m=admin&c=index&a=Lists&catID=1&page=1#top';var_export(parse_url($url));
返回:
array ( 'scheme' => 'http', 'host' => 'localhost', 'path' => '/test.PHP', 'query' => 'm=admin&c=index&a=Lists&catID=1&page=1', 'fragment' => 'top',)
4、利用basename内置函数
echo "<pre>";$url = 'http://localhost/test.PHP?m=admin&c=index&a=Lists&catID=1&page=1#top';var_export(basename($url));
返回:
test.PHP?m=admin&c=index&a=Lists&catID=1&page=1#top
5、正则匹配
echo "<pre>";$url = 'http://localhost/test.PHP?m=admin&c=index&a=Lists&catID=1&page=1#top';preg_match_all("/(\w+=\w+)(#\w+)?/i",$url,$match);var_export($match);
返回:
array ( 0 => array ( 0 => 'm=admin', 1 => 'c=index', 2 => 'a=Lists', 3 => 'catID=1', 4 => 'page=1#top', ), 1 => array ( 0 => 'm=admin', 1 => 'c=index', 2 => 'a=Lists', 3 => 'catID=1', 4 => 'page=1', ), 2 => array ( 0 => '', 1 => '', 2 => '', 3 => '', 4 => '#top', ),)
url常用处理方法
/** * 将字符串参数变为数组 * @param $query * @return array */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 */function getUrlquery($array_query){ $tmp = array(); foreach ($array_query as $k => $param) { $tmp[] = $k . '=' . $param; } $params = implode('&', $tmp); return $params;}
例:
echo "<pre>";$url = 'http://localhost/test.PHP?m=admin&c=index&a=Lists&catID=1&page=1#top';$arr = parse_url($url);$arr_query = convertUrlquery($arr['query']);var_export($arr_query);
返回:
array ( 'm' => 'admin', 'c' => 'index', 'a' => 'Lists', 'catID' => '1', 'page' => '1',)
var_export(getUrlquery($arr_query));
返回:
m=admin&c=index&a=Lists&catID=1&page=1
相关教程推荐:《PHP教程》 总结
以上是内存溢出为你收集整理的php如何解析url?解析url的5种方式介绍全部内容,希望文章能够帮你解决php如何解析url?解析url的5种方式介绍所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)