Skip to content

Instantly share code, notes, and snippets.

@phpfiddle
Created February 20, 2018 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phpfiddle/4f69c00102f5a47c0bdba853d65b3a7b to your computer and use it in GitHub Desktop.
Save phpfiddle/4f69c00102f5a47c0bdba853d65b3a7b to your computer and use it in GitHub Desktop.
<?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