tags:

views:

62

answers:

2

Hi,

I need to get the domain name from a URL. Examples:

google.com
images.google.com
new.images.google.com
www.google.com

should all return google.com

Also

google.co.uk
images.google.co.uk
new.images.google.co.uk
http://www.google.co.uk

should all return google.co.uk

I'm hesitant to use Regular Expressions, because something like domain.com/google.com could return incorrect results.

So, how can I get the top-level domain, using PHP? This needs to work on all platforms and hosts.

Thanks!

+1  A: 

Try using: http://php.net/manual/en/function.parse-url.php. Something like this should work:

$urlParts = parse_url($yourUrl);
$hostParts = explode('.', $urlParts['host']);
$hostParts = array_reverse($hostParts);
$host = $hostParts[1] . '.' . $hostParts[0];
ksangers
That would break if you have something like this: http://www.google.co.uk - in that case, it'd return "co.uk".
xil3
It would indeed, the only way to get that sorted though is by using a TLD list.
ksangers
+2  A: 

You could do this:

$urlData = parse_url($url);

$host = $urlData['host'];

** Update **

The best way I can think of is to have a mapping of all the TLDs that you want to handle, since certain TLDs can be tricky (co.uk).

// you can add more to it if you want
$urlMap = array('com', 'co.uk');

$host = "";
$url = "http://www.google.co.uk";

$urlData = parse_url($url);
$hostData = explode('.', $urlData['host']);
$hostData = array_reverse($hostData);

if(array_search($hostData[1] . '.' . $hostData[0], $urlMap) !== FALSE) {
  $host = $hostData[2] . '.' . $hostData[1] . '.' . $hostData[0];
} elseif(array_search($hostData[0], $urlMap) !== FALSE) {
  $host = $hostData[1] . '.' . $hostData[0];
}

echo $host;
xil3
Input: http://images.google.comOutput: images.google.comDoesn't work :(
Rohan
I'll change the answer with a better solution for you.
xil3
Thanks! Appreciate it
Rohan
Ok, just added an update.
xil3
Thank you so much! This works great.
Rohan