Joy*_*abu 11
preg_match('/(.*?)((?:\.co)?.[a-z]{2,4})$/i', $domain, $matches);
Run Code Online (Sandbox Code Playgroud)
$ matches [1]将拥有域名,$ matches [2]将拥有该域名
<?php
$domains = array("google.com", "google.in", "google.co.in", "google.info", "analytics.google.com");
foreach($domains as $domain){
preg_match('/(.*?)((?:\.co)?.[a-z]{2,4})$/i', $domain, $matches);
print_r($matches);
}
?>
Run Code Online (Sandbox Code Playgroud)
会产生输出
Array
(
[0] => google.com
[1] => google
[2] => .com
)
Array
(
[0] => google.in
[1] => google
[2] => .in
)
Array
(
[0] => google.co.in
[1] => google
[2] => .co.in
)
Array
(
[0] => google.info
[1] => google
[2] => .info
)
Array
(
[0] => analytics.google.com
[1] => analytics.google
[2] => .com
)
Run Code Online (Sandbox Code Playgroud)
$subject = 'just-a.domain.com';
$result = preg_split('/(?=\.[^.]+$)/', $subject);
Run Code Online (Sandbox Code Playgroud)
这会生成以下数组
$result[0] == 'just-a.domain';
$result[1] == '.com';
Run Code Online (Sandbox Code Playgroud)
如果要删除域名注册商管理的域名部分,则需要使用公共后缀列表等后缀列表.
但是,由于遍历此列表并测试域名上的后缀并不是那么有效,而是仅使用此列表来构建这样的索引:
$tlds = array(
// ac : http://en.wikipedia.org/wiki/.ac
'ac',
'com.ac',
'edu.ac',
'gov.ac',
'net.ac',
'mil.ac',
'org.ac',
// ad : http://en.wikipedia.org/wiki/.ad
'ad',
'nom.ad',
// …
);
$tldIndex = array_flip($tlds);
Run Code Online (Sandbox Code Playgroud)
搜索最佳匹配将如下所示:
$levels = explode('.', $domain);
for ($length=1, $n=count($levels); $length<=$n; ++$length) {
$suffix = implode('.', array_slice($levels, -$length));
if (!isset($tldIndex[$suffix])) {
$length--;
break;
}
}
$suffix = implode('.', array_slice($levels, -$length));
$prefix = substr($domain, 0, -strlen($suffix) - 1);
Run Code Online (Sandbox Code Playgroud)
或者构建一个表示域名级别层次结构的树,如下所示:
$tldTree = array(
// ac : http://en.wikipedia.org/wiki/.ac
'ac' => array(
'com' => true,
'edu' => true,
'gov' => true,
'net' => true,
'mil' => true,
'org' => true,
),
// ad : http://en.wikipedia.org/wiki/.ad
'ad' => array(
'nom' => true,
),
// …
);
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下内容查找匹配项:
$levels = explode('.', $domain);
$r = &$tldTree;
$length = 0;
foreach (array_reverse($levels) as $level) {
if (isset($r[$level])) {
$r = &$r[$level];
$length++;
} else {
break;
}
}
$suffix = implode('.', array_slice($levels, - $length));
$prefix = substr($domain, 0, -strlen($suffix) - 1);
Run Code Online (Sandbox Code Playgroud)