Skip to content
Advertisement

Parsing domain from a URL

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.

Advertisement

Answer

Check out parse_url():

$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement