【问题标题】:Get domain name from url without tld从没有 tld 的 url 获取域名
【发布时间】:2013-10-17 16:09:52
【问题描述】:

我需要知道如何在没有 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" 当我需要它显示 "example"

谢谢

【问题讨论】:

标签: php dns tld


【解决方案1】:

Regex 是错误的解决方案,您需要使用 Public Suffix List 进行打包,只有使用它才能在复杂的 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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-07
    • 2012-08-10
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多