获取url中的顶级域名

public function getTopHost($url){
    $url = strtolower($url);  //首先转成小写
    $hosts = parse_url($url);
    $host = $hosts['host'];
    //查看是几级域名
    $data = explode('.', $host);
    $n = count($data);
    //判断是否是双后缀
    $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
    if(($n > 2) && preg_match($preg,$host)){
        //双后缀取后3位
        $host = $data[$n-3].'.'.$data[$n-2].'.'.$data[$n-1];
    }else{
        //非双后缀取后两位
        $host = $data[$n-2].'.'.$data[$n-1];
    }
  return $host;
}
最后修改:2020 年 11 月 11 日
如果觉得我的文章对你有用,请随意赞赏