Split an URL into protocol, site, and resource parts


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  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. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.