Skip to content

Instantly share code, notes, and snippets.

@ivikramsahu
Last active March 8, 2021 07:12
Show Gist options
  • Save ivikramsahu/b5b45e909fca3ccb1bfb6fc9ab61040d to your computer and use it in GitHub Desktop.
Save ivikramsahu/b5b45e909fca3ccb1bfb6fc9ab61040d to your computer and use it in GitHub Desktop.
Extracting main domain from url having subdomain (works with <any number of subdomain>.maindomain.<com|org|co>.<in|uk|ng|dl>)
<?php
echo "Running Domain extraction script at ".date('Y-m-d H:i:s')."\n\n";
if(empty($argv[1])){
echo "please enter in below format \n php domain-from-subdomain.php http://<subdomain/domain name>/xyz/mypath/to/some/image/folder\n";
exit;
}else{
if(explode(":",$argv[1])[0] == "http" || explode(":",$argv[1])[0] == "https"){
print get_domain($argv[1]);
}else{
echo "Please pass a valid url:\neg.\n1. https://<subdomain-if-any>.example.org \n2. https://<subdomain-if-any>.example.com\n";
}
}
function get_domain($url)
{
$infoArr = parse_url($url);
$domain = isset($infoArr['host']) ? $infoArr['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{1,6})$/i', $domain, $dataInRegex)) {
return $dataInRegex['domain'];
}
return false;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment