Мы используем эту функцию для обработки нескольких субдоменов и нескольких tld , а также для обработки ip и localhost
function analyse_host($_host)
{
$my_host = explode('.', $_host);
$my_result = ['subdomain' => null, 'root' => null, 'tld' => null];
// if host is ip, only set as root
if(filter_var($_host, FILTER_VALIDATE_IP))
{
// something like 127.0.0.5
$my_result['root'] = $_host;
}
elseif(count($my_host) === 1)
{
// something like localhost
$my_result['root'] = $_host;
}
elseif(count($my_host) === 2)
{
// like jibres.com
$my_result['root'] = $my_host[0];
$my_result['tld'] = $my_host[1];
}
elseif(count($my_host) >= 3)
{
// some conditons like
// ermile.ac.ir
// ermile.jibres.com
// ermile.jibres.ac.ir
// a.ermile.jibres.ac.ir
// get last one as tld
$my_result['tld'] = end($my_host);
array_pop($my_host);
// check last one after remove is probably tld or not
$known_tld = ['com', 'org', 'net', 'gov', 'co', 'ac', 'id', 'sch', 'biz'];
$probably_tld = end($my_host);
if(in_array($probably_tld, $known_tld))
{
$my_result['tld'] = $probably_tld. '.'. $my_result['tld'];
array_pop($my_host);
}
$my_result['root'] = end($my_host);
array_pop($my_host);
// all remain is subdomain
if(count($my_host) > 0)
{
$my_result['subdomain'] = implode('.', $my_host);
}
}
return $my_result;
}