PHP Getting Domain Name From Subdomain

Stackoverflow Question Archive:

  • How to get domain name from url?
  • Check if domain equals value?
  • How do I get the base url?

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

Tags:

Php

Dns

Subdomain