We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

dbug13 on 05/31/08


Tagged

php textmate


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

heinz1959
ishkur


Split an URL into protocol, site, and resource parts


Published in: PHP 


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

Report this snippet 

You need to login to post a comment.