将URL拆分为协议站点和资源部分

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将URL拆分为协议站点和资源部分相关的知识,希望对你有一定的参考价值。

  1. <?php
  2. /**
  3.  * Takes an URL and splits it up into it's protocol, site, and resource parts
  4.  *
  5.  * Returns an associative array of protocol, port, site, and resource parts
  6.  * Note: the URL does not have to have a protocol specified
  7.  * example:
  8.  * <code>
  9.  * $url = "http://www.foo.com/blog/search?q=bar";
  10.  * $url_parts = getUrlParts($url);
  11.  * // $url_parts will contain the following:
  12.  * // Array
  13.  * // (
  14.  * // [protocol] => http
  15.  * // [port] =>
  16.  * // [site] => www.foo.com
  17.  * // [resource] => blog/search?q=bar
  18.  * // )
  19.  *
  20.  * $url = "www.foo.com:8080/blog/search?q=bar";
  21.  * $url_parts = getUrlParts($url);
  22.  * // $url_parts will contain the following:
  23.  * // Array
  24.  * // (
  25.  * // [protocol] =>
  26.  * // [port] => 8080
  27.  * // [site] => www.foo.com
  28.  * // [resource] => blog/search?q=bar
  29.  * // )
  30.  * </code>
  31.  *
  32.  * @param string The URL that you want to split up
  33.  * @return associative array Array containing the split up parts of the URL
  34.  */
  35. function getUrlParts($url) {
  36. $result = array();
  37.  
  38. // Get the protocol, site and resource parts of the URL
  39. // original url = http://example.com/blog/index?name=foo
  40. // protocol = http://
  41. // site = example.com/
  42. // resource = blog/index?name=foo
  43. $regex = '#^(.*?//)*([w.d]*)(:(d+))*(/*)(.*)$#';
  44. $matches = array();
  45. preg_match($regex, $url, $matches);
  46.  
  47. // Assign the matched parts of url to the result array
  48. $result['protocol'] = $matches[1];
  49. $result['port'] = $matches[4];
  50. $result['site'] = $matches[2];
  51. $result['resource'] = $matches[6];
  52.  
  53. // clean up the site portion by removing the trailing /
  54. $result['site'] = preg_replace('#/$#', '', $result['site']);
  55.  
  56. // clean up the protocol portion by removing the trailing ://
  57. $result['protocol'] = preg_replace('#://$#', '', $result['protocol']);
  58.  
  59. return $result;
  60. }
  61. ?>

以上是关于将URL拆分为协议站点和资源部分的主要内容,如果未能解决你的问题,请参考以下文章

将url拆分为多个部分

JQuery Datatable - 将单个单元格拆分为多列以提高可读性?

我们如何将浮点数拆分为整数和小数部分?

如何将字符串拆分为多个部分?

PHP PHP将数字拆分为整数和小数部分

url 上的正则表达式无法在没有 GET 参数的情况下拆分散列