Wednesday, 14 August 2013

How to get the naked domain from a given URL or hostname in PHP? [duplicate]

How to get the naked domain from a given URL or hostname in PHP? [duplicate]

This question already has an answer here:
PHP Getting Domain Name From Subdomain 18 answers
Basically I need to extract the naked domain from a given URL / hostname:
http://www.google.com => google.com
http://www.google.com.sg => google.com.sg
http://www.bbc.co.uk => bbc.co.uk
http://abc.tumblr.com => tumblr.com
http://list.qoo10.sg => qoo10.sg
My current code:
function get_naked_domain($url) {
$tld = array('com','co','gov','edu'); // Need a more complete list
$cc = array('uk','sg',.... ); // Country code list
$host = parse_url($url,PHP_URL_HOST);
$parts = explode('.',$host);
$len = count($parts);
if (in_array($parts[$len-1],$cc)) && in_array($parts[$len-2],$tld)) {
$naked_domain = implode('.',array_slice($parts,-3));
} else {
$naked_domain = implode('.',array_slice($parts,-2));
}
return $naked_domain;
}
Is there a better approach? If no, where can I find a complete list of Top
Level Domains that can have optional country code? I realized that not all
TLD can have country code. (e.g. .asia, .me can't have country code
behind?)
Note: I have checked out other similar question but couldn't find a
satisfactory solution.

No comments:

Post a Comment