假设我有just-a.domain.com,just-a-domain.info,just.a-domain.net,如何删除扩展名.com,.net.info ...,我需要两个变量中的结果,一个是域名,另一个是扩展名。
我尝试过使用str_replace,但不起作用,我猜只能使用正则表达式....
发布于 2010-10-04 15:31:22
$subject = 'just-a.domain.com';
$result = preg_split('/(?=\.[^.]+$)/', $subject);这将生成以下数组
$result[0] == 'just-a.domain';
$result[1] == '.com';发布于 2010-10-04 15:49:45
preg_match('/(.*?)((?:\.co)?.[a-z]{2,4})$/i', $domain, $matches);$matches1将具有域名,而$matches2将具有扩展名
<?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);
}
?>将产生输出
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
)发布于 2010-10-04 15:51:36
如果您想要删除域名注册商管理的域名部分,您将需要使用类似于the Public Suffix List的后缀列表。
但是,由于遍历此列表并测试域名的后缀效率不高,因此只能使用此列表来构建索引,如下所示:
$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);搜索最佳匹配的过程如下所示:
$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);或者构建一个树,表示域名级别的层次结构,如下所示:
$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,
),
// …
);然后,您可以使用以下内容查找匹配项:
$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);https://stackoverflow.com/questions/3853338
复制相似问题