zuk1 zuk1 - 5 months ago 26
PHP Question

Parsing Domain From URL In PHP

I need to build a function which parses the domain from a URL.

So, with

http://google.com/dhasjkdas/sadsdds/sdda/sdads.html


or

http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html


it should return
google.com


with

http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html


it should return
google.co.uk
.

Answer

Check out parse_url():

$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
print $parse['host']; // prints 'google.com'

parse_url doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls.