Created
February 20, 2018 14:17
-
-
Save phpfiddle/4f69c00102f5a47c0bdba853d65b3a7b to your computer and use it in GitHub Desktop.
[ Posted by Faizan ] getTopLevelDomain in php https://stackoverflow.com/questions/3211411/how-to-get-the-base-domain-name-from-an-url-using-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
<?php | |
function getTopLevelDomain($url){ | |
$urlData = parse_url($url); | |
$urlHost = isset($urlData['host']) ? $urlData['host'] : ''; | |
$isIP = (bool)ip2long($urlHost); | |
if($isIP){ /** To check if it's ip then return same ip */ | |
return $urlHost; | |
} | |
$urlMap = array('com', 'com.pk', 'co.uk'); | |
$host = ""; | |
$hostData = explode('.', $urlHost); | |
if(isset($hostData[1])){ /** To check "localhost" because it'll be without any tld */ | |
$hostData = array_reverse($hostData); | |
if(array_search($hostData[1] . '.' . $hostData[0], $urlMap) !== FALSE) { | |
$host = $hostData[2] . '.' . $hostData[1] . '.' . $hostData[0]; | |
} elseif(array_search($hostData[0], $urlMap) !== FALSE) { | |
$host = $hostData[1] . '.' . $hostData[0]; | |
} | |
return $host; | |
} | |
return (isset($hostData[0]) ? $hostData[0] : 'error no domain'); /* You can change this error in future */ | |
} | |
$string = 'http://googl.com.pk'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://googl.com.pk:23'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://googl.com'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://googl.com:23'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://adad.asdasd.googl.com.pk'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://adad.asdasd.googl.com.pk:23'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://adad.asdasd.googl.com'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://adad.asdasd.googl.com:23'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://192.168.0.101:23'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://192.168.0.101'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'http://localhost'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = 'https;//'; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
$string = ''; | |
echo getTopLevelDomain( $string ) . '<br>'; | |
/** | |
* You'll get answers like this | |
* googl.com.pk | |
* googl.com.pk | |
* googl.com | |
* googl.com | |
* googl.com.pk | |
* googl.com.pk | |
* googl.com | |
* googl.com | |
* 192.168.0.101 | |
* 192.168.0.101 | |
* localhost | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment