php如何解析url?解析url的5种方式介绍

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内置函数

  1. echo "<pre>";
  2. $url = 'http://localhost/test.php?m=admin&c=index&a=lists&cat;
  3. var_export(pathinfo($url));

返回:

  1. array (
  2. 'dirname' => 'http://localhost',
  3. 'basename' => 'test.php?m=admin&c=index&a=lists&cat,
  4. 'extension' => 'php?m=admin&c=index&a=lists&cat,
  5. 'filename' => 'test',
  6. )

3、利用parse_url内置函数

  1. echo "<pre>";
  2. $url = 'http://localhost/test.php?m=admin&c=index&a=lists&cat;
  3. var_export(parse_url($url));

返回:

  1. array (
  2. 'scheme' => 'http',
  3. 'host' => 'localhost',
  4. 'path' => '/test.php',
  5. 'query' => 'm=admin&c=index&a=lists&cat,
  6. 'fragment' => 'top',
  7. )

4、利用basename内置函数

  1. echo "<pre>";
  2. $url = 'http://localhost/test.php?m=admin&c=index&a=lists&cat;
  3. var_export(basename($url));

返回:

test.php?m=admin&c=index&a=lists&catid=1&page=1#top

5、正则匹配

  1. echo "<pre>";
  2. $url = 'http://localhost/test.php?m=admin&c=index&a=lists&cat;
  3. preg_match_all("/(\w+=\w+)(#\w+)?/i",$url,$match);
  4. var_export($match);

返回:

  1. array (
  2. 0 =>
  3. array (
  4. 0 => 'm=admin',
  5. 1 => 'c=index',
  6. 2 => 'a=lists',
  7. 3 => 'cat,
  8. 4 => 'page=1#top',
  9. ),
  10. 1 =>
  11. array (
  12. 0 => 'm=admin',
  13. 1 => 'c=index',
  14. 2 => 'a=lists',
  15. 3 => 'cat,
  16. 4 => 'page=1',
  17. ),
  18. 2 =>
  19. array (
  20. 0 => '',
  21. 1 => '',
  22. 2 => '',
  23. 3 => '',
  24. 4 => '#top',
  25. ),
  26. )

url常用处理方法

  1. /**
  2. * 将字符串参数变为数组
  3. * @param $query
  4. * @return array
  5. */
  6. function convertUrlQuery($query)
  7. {
  8. $queryParts = explode('&', $query);
  9. $params = array();
  10. foreach ($queryParts as $param) {
  11. $item = explode('=', $param);
  12. $params[$item[0]] = $item[1];
  13. }
  14. return $params;
  15. }
  16. /**
  17. * 将参数变为字符串
  18. * @param $array_query
  19. * @return string
  20. */
  21. function getUrlQuery($array_query)
  22. {
  23. $tmp = array();
  24. foreach ($array_query as $k => $param) {
  25. $tmp[] = $k . '=' . $param;
  26. }
  27. $params = implode('&', $tmp);
  28. return $params;
  29. }

例:

  1. echo "<pre>";
  2. $url = 'http://localhost/test.php?m=admin&c=index&a=lists&cat;
  3. $arr = parse_url($url);
  4. $arr_query = convertUrlQuery($arr['query']);
  5. var_export($arr_query);

返回:

  1. array (
  2. 'm' => 'admin',
  3. 'c' => 'index',
  4. 'a' => 'lists',
  5. 'catid' => '1',
  6. 'page' => '1',
  7. )
  8. var_export(getUrlQuery($arr_query));

返回:

m=admin&c=index&a=lists&catid=1&page=1