Created
July 9, 2012 16:11
-
-
Save strangerstudios/3077376 to your computer and use it in GitHub Desktop.
Get a Domain from a URL in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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