PHP Getting Domain Name From Subdomain
Stackoverflow Question Archive:
print get_domain("http://somedomain.co.uk"); // outputs 'somedomain.co.uk'function get_domain($url){ $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } return false;}
If you want a fast simple solution, without external calls and checking against predefined arrays. Works for new domains like "www.domain.gallery" also, unlike the most popular answer.
function get_domain($host){ $myhost = strtolower(trim($host)); $count = substr_count($myhost, '.'); if($count === 2){ if(strlen(explode('.', $myhost)[1]) > 3) $myhost = explode('.', $myhost, 2)[1]; } else if($count > 2){ $myhost = get_domain(explode('.', $myhost, 2)[1]); } return $myhost;}
- domain.com -> domain.com
- sub.domain.com -> domain.com
- www.domain.com -> domain.com
- www.sub.sub.domain.com -> domain.com
- domain.co.uk -> domain.co.uk
- sub.domain.co.uk -> domain.co.uk
- www.domain.co.uk -> domain.co.uk
- www.sub.sub.domain.co.uk -> domain.co.uk
- domain.photography -> domain.photography
- www.domain.photography -> domain.photography
- www.sub.domain.photography -> domain.photography
I would do something like the following:
// hierarchical array of top level domains$tlds = array( 'com' => true, 'uk' => array( 'co' => true, // … ), // …);$domain = 'here.example.co.uk';// split domain$parts = explode('.', $domain);$tmp = $tlds;// travers the tree in reverse order, from right to leftforeach (array_reverse($parts) as $key => $part) { if (isset($tmp[$part])) { $tmp = $tmp[$part]; } else { break; }}// build the resultvar_dump(implode('.', array_slice($parts, - $key - 1)));