用PHP判断顶级域名


在写电商圈排名系统时,其中一个重要的想法就是要判断顶级域名,即一级域名的。 因为在电商圈百度排名里,各种各样的URL都是有的,如:

  • 二级域名:q.eb.cn
  • 内页:http://yun.im/yunseo/621.html

其它等等。

而在统计排名时,只计算顶级域名的。其它非顶级域名则排除。 所以关键一步就是判断顶级域名的正确性。前期的代码有些BUG,不过现在已经修复了。分享一些几个自定义的函数。

用PHP判断一级域名

第一步,先把域名变为短域名,从wordpress学来的。

如把http://yun.im/变成yun.im,或是把http://yun.im/blog变成yun.im/blog,或是把http://www.liucheng.name/ 变为 liucheng.name

function yunim_short_url($url){     

$short_url = str_replace('http://', '', $url);     

$short_url = preg_replace('/^www\./i', '', $short_url);     

if ('/' == substr($short_url, -1)) 

{

$short_url = substr($short_url, 0, -1);

 }     

return $short_url;

}

第二步,对短域名进行过滤。把一些组合的域名后缀替换一下先。如.com.cn, .net.cn,  .com.hk等等组合的域名后缀。根据需要可以增加。

function yunim_special_url($short_url){     

## com.cn   net.cn  gov.cn  org.cn  com.hk  com.tw     

$special_url = array('.com.cn', '.net.cn', '.gov.cn', '.org.cn', '.com.hk', '.com.tw');  ##这里根据需要继续添加     

preg_match_all('/\./', $short_url, $match);     

if( count($match[0])==2 && !preg_match('/\//', $short_url) )

{         

$short_url = str_replace( $special_url, '.com', $short_url );    

 }     

return $short_url;

}

第三步,替换完了后,再对域名进行判断。没有斜杠(/),以及点(.)的数量才1个的。就判断为顶级域名,即一级域名。

function yunim_is_url($short_url){     

##判断域名 是否是一级域名     

$short_url = yunim_special_url($short_url);     

preg_match_all('/\./', $short_url, $match);     

if( count($match[0])==1 && !preg_match('/\//', $short_url) )

{         

return 1;     

}else{         

return 0;     

}

}

例子:

$url_1 = 'http://yun.im/'; ##或是$url_2 = 'http://q.eb.cn/';

echo yunim_is_url(yunim_short_url($url_1));

如果是url_1的话就会输出1,即TRUE,如果是url_2的话就会输出0,即FALSE。

大功告成。  不过还是觉得有些麻烦的样子。如果有好的建议,欢迎留言。

详细见原文:http://yun.im/yunseo/621.html


《 “用PHP判断顶级域名” 》 有 51 条评论

  1. function getdomain(){
    $host=$_SERVER[HTTP_HOST];
    $host=strtolower($host);
    if(strpos($host,’/’)!==false){
    $parse = @parse_url($host);
    $host = $parse[’host’];
    }
    $topleveldomaindb=array(’com’,’edu’,’gov’,’int’,’mil’,’net’,’org’,’biz’,’info’,’pro’,’name’,’museum’,’coop’,’aero’,’xxx’,’idv’,’mobi’,’cc’,’me’);
    $str=’’;
    foreach($topleveldomaindb as $v){
    $str.=($str ? ’|’ : ’’).$v;
    }
    $matchstr=”[^.]+.(?:(“.$str.”)|w{2}|((“.$str.”).w{2}))$”;
    if(preg_match(“/”.$matchstr.”/ies”,$host,$matchs)){
    $domain=$matchs[’0’];
    }else{
    $domain=$host;
    }
    return $domain;
    }

    搞来搞去。和这段代码是一样的。。