With this PHP function you can extract out the domain name from a URL or sub domain string. This function supports extracting out the TLD (top level domain such as com, org, net), the SLD (second level domain such as google.com, yahoo.com, bing.com), or any level of subdomains after that. You can either return the name only (e.g. google, yahoo, bing) for the level you are after, or the fully qualified domain name (eg. google.com, yahoo.com, bing.com). If you are needing a function which automatically separates out the gTLD or ccTLD according to the Public Suffix List, you will need a more sophisticated library such as TLDExtract that is also written in PHP.

/**
 * Takes a URL or domain name and figures out the tld (top level domain), sld (second level domain), or any level of
 * subdomains after that. You can return the corresponding level's name only, or the FQDN (fully qualified domain name).
 *
 * @param string $url A full URL or domain name
 * @param int $level The level of domain you are wanting to extract with 1 being the TLD such as com, org, net.
 * @param bool $nameOnly Return only the corresponding level's name only
 * @return string|null Returns null if no valid tld, sld, or other is found
 */
function getDomain($url, $level = 2, $nameOnly = false)
{
    $host = parse_url('http://' . preg_replace('#^https?://#', '', $url), PHP_URL_HOST);
    $parts = explode(".", $host);

    if($level < 1 || count($parts) < $level) {
        return null;
    }

    if($nameOnly) {
        return $parts[count($parts) - $level];
    }

    return implode('.', array_slice($parts, -$level));
}

This code snippet was published on It was last edited on

0

0 Comments

  • Votes
  • Oldest
  • Latest