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
2
  • 3
    there is a function for that: parse_url() Commented Dec 18, 2012 at 23:45
  • @Dagon That would make a perfect answer rather than a comment :) Commented Dec 18, 2012 at 23:47

2 Answers 2

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

See also parse_str 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.
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. 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.