0

How can I utilize preg_replace in PHP to parse a url.

Say I have the url

http://google.com?id=123

and I want to access each part of the url such that

echo $protocol;

would print

http

or

echo $domain;

would print

google

and

echo $upperDomain;

prints

com

and finally,

echo $rest;

would print

?id=123
Cripto
  • 3,581
  • 7
  • 41
  • 65

2 Answers2

4

there is a function for that: parse_url()

$url = 'http://google.com?id=123';    
print_r(parse_url($url));

prints:

Array
(
    [scheme] => http
    [host] => google.com
    [query] => id=123
)
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
  • See also [parse_str](http://php.net/manual/en/function.parse-str.php) if you want to parse the query string too. Additionally, if you're interested in separating the TLD and the secondary domain, you might want to look at [this question](http://stackoverflow.com/questions/288810/get-the-subdomain-from-a-url). – cmbuckley Dec 18 '12 at 23:55
0

parse_url() from the docs...

 mixed parse_url ( string $url [, int $component = -1 ] )

This function parses a URL and returns an associative array containing any of the   
various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the 
above listed parts. Partial URLs are also accepted, parse_url() tries its best to   
parse them correctly. 
Pedro del Sol
  • 2,840
  • 9
  • 39
  • 52