根据公共后缀列表从URL中提取注册域

时间:2011-11-25 18:03:28

标签: php url domain-name

根据网址,如何使用Public Suffix List(有效顶级域名列表,例如this list)提取注册域名?

例如,考虑a.bg是有效的公共后缀:

http://www.test.start.a.bg/hello.html -> start.a.bg 
http://test.start.a.bg/               -> start.a.bg
http://test.start.abc.bg/             -> abc.bg (.bg is the public suffix)

使用简单的字符串操作无法完成此操作,因为公共后缀可能包含多个级别,具体取决于TLD。

P.S。无论我如何阅读列表(数据库或平面文件),但列表应该可以在本地访问,所以我并不总是依赖于外部服务。

3 个答案:

答案 0 :(得分:16)

您可以使用parse_url()提取主机名,然后使用library provided by regdom确定注册的域名(dn + eTLD)。例如:

require_once("effectiveTLDs.inc.php");
require_once("regDomain.inc.php");

$url =  'http://www.metu.edu.tr/dhasjkdas/sadsdds/sdda/sdads.html';
echo getRegisteredDomain(parse_url($url, PHP_URL_HOST));

这将打印出metu.edu.tr

我尝试过的其他例子:

http://www.xyz.start.bg/hello   ->   start.bg
http://www.start.a.bg/world     ->   start.a.bg  (a.bg is a listed eTLD)
http://xyz.ma219.metu.edu.tr    ->   metu.edu.tr
http://www.google.com/search    ->   google.com
http://google.co.uk/search?asd  ->   google.co.uk

更新:这些库已移至:https://github.com/leth/registered-domains-php

答案 1 :(得分:4)

这个问题有点陈旧,但有一个新的解决方案:https://github.com/jeremykendall/php-domain-parser

这个库完全符合您的要求。这是设置:

$pslManager = new Pdp\PublicSuffixListManager();
$parser = new Pdp\Parser($pslManager->getList());
echo $parser->getRegisterableDomain('www.scottwills.co.uk');

这将打印"scottwills.co.uk"

答案 2 :(得分:1)

我建议使用TLDExtract,它具有从PSL生成的可重新更新的数据库。

$extract = new LayerShifter\TLDExtract\Extract();

$result = $extract->parse('shop.github.com');
$result->getFullHost(); // will return (string) 'shop.github.com'
$result->getRegistrableDomain(); // will return (string) 'github.com'
$result->isValidDomain(); // will return (bool) true
$result->isIp(); // will return (bool) false