Skip to content

Instantly share code, notes, and snippets.

@strangerstudios
Created July 9, 2012 16:11
Show Gist options
  • Save strangerstudios/3077376 to your computer and use it in GitHub Desktop.
Save strangerstudios/3077376 to your computer and use it in GitHub Desktop.
Get a Domain from a URL in PHP
/**
* Get the "domain" from a URL. By domain, we mean the host name, minus any subdomains. So just the domain and TLD.
*
* @param string $url The URL to parse. (generally pass site_url() in WP)
* @return string The domain.
*/
function getDomainFromURL($url = NULL)
{
$domainparts = parse_url($url);
$domainparts = explode(".", $domainparts['host']);
if(count($domainparts) > 1)
{
//check for ips
$isip = true;
foreach($domainparts as $part)
{
if(!is_numeric($part))
{
$isip = false;
break;
}
}
if($isip)
{
//ip, e.g. 127.1.1.1
$domain = implode(".", $domainparts);
}
else
{
//www.something.com, etc.
$domain = $domainparts[count($domainparts)-2] . "." . $domainparts[count($domainparts)-1];
}
}
else
{
//localhost or another single word domain
$domain = $domainparts[0];
}
return $domain;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment