从没有 tld 的网址获取域名


Get domain name from url without tld

我需要知道如何从没有 tld 的 url 中获取域名。

这就是我所拥有的适用于.com、.info 等,但不适用于 .co.uk

// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i',
"http://example.co.uk", $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/([^.]+)'.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[1]}'n";

当我让它调用"example.co.uk"域时,它只显示:"co",当我需要它显示"示例"

谢谢

Regex 是那里的虚假解决方案,您需要使用公共后缀列表的包,只有有了它,您才能在复杂的 TLDS 上获得正确的结果。

我推荐TLDExtract进行域解析,以下是显示差异的示例代码:

$extract = new LayerShifter'TLDExtract'Extract();
# For 'http://www.domain.com/site'
$result = $extract->parse('http://www.domain.com/site');
$result->getFullHost(); // will return 'www.domain.com'
$result->getRegistrableDomain(); // will return 'domain.com'
$result->getSuffix(); // will return 'com'
# For 'http://www.domain.co.uk/site'
$result = $extract->parse('http://www.domain.co.uk/site');
$result->getFullHost(); // will return 'www.domain.co.uk'
$result->getRegistrableDomain(); // will return 'domain.co.uk'
$result->getSuffix(); // will return 'co.uk'