PHP获取顶级域名,获取域名级别,更正版!v3

版本v1: http://blog.csdn.net/default7/article/details/8247785
版本v2: http://blog.csdn.net/default7/article/details/8249383

 

前2次写的其实不太好,使用起来不是很方便。今天突然发现一个问题,如果当域名为www.***.com时候,他的顶级域名应该是***.com,而不是www.****.com。当时的写法故意把顶级域名设定为了www.***.com。后来带来了很多不方便。更正后的代码:

注意:代码高亮highlight的时候第7行empty那里总是多显示一个empty,可以直接点击查看源码。

if(!function_exists("parseHost"))
{
  function parseHost($httpurl)
  {

    $httpurl = strtolower( trim($httpurl) );
    if(empty($httpurl)) return ;
    $regx1 = '/https?:\/\/(([^\/\?#&]+\.)?([^\/\?#&\.]+\.)(com\.cn|org\.cn|net\.cn|com\.jp|co\.jp|com\.kr|com\.tw)(\:[0-9]+)?)\/?/i';
    $regx2 = '/https?:\/\/(([^\/\?#&]+\.)?([^\/\?#&\.]+\.)(cn|com|org|info|us|fr|de|tv|net|cc|biz|hk|jp|kr|name|me|tw|la)(\:[0-9]+)?)\/?/i';
    $host = $tophost = '';
    if(preg_match($regx1,$httpurl,$matches))
    {
      $host = $matches[1];
    } elseif(preg_match($regx2, $httpurl, $matches)) {
      $host = $matches[1];
    }
    if($matches)
    {
    	$tophost = $matches[3].$matches[4];
    	$domainLevel = $matches[2] == 'www.' ? 1:(substr_count($matches[2],'.')+1);
    } else {
    	$tophost = '';
    	$domainLevel = 0;
    }
    return array($domainLevel,$tophost,$host);
  }
}

测试代码:

<?php

  function parseHost($httpurl)
  {
  	
    $httpurl = strtolower( trim($httpurl) );
    if(empty($httpurl)) return ;
    $regx1 = '/https?:\/\/(([^\/\?#&]+\.)?([^\/\?#&\.]+\.)(com\.cn|org\.cn|net\.cn|com\.jp|co\.jp|com\.kr|com\.tw)(\:[0-9]+)?)\/?/i';
    $regx2 = '/https?:\/\/(([^\/\?#&]+\.)?([^\/\?#&\.]+\.)(cn|com|org|info|us|fr|de|tv|net|cc|biz|hk|jp|kr|name|me|tw|la)(\:[0-9]+)?)\/?/i';
    $host = $tophost = '';
    if(preg_match($regx1,$httpurl,$matches))
    {
      $host = $matches[1];
    } elseif(preg_match($regx2, $httpurl, $matches)) {
      $host = $matches[1];
    }   
    if($matches) 
    {
    	$tophost = $matches[3].$matches[4];
    	$domainLevel = $matches[2] == 'www.' ? 1:(substr_count($matches[2],'.')+1);	
    } else {
    	$tophost = '';
    	$domainLevel = 0;
    }
    print_r($matches);
    return array($domainLevel,$tophost,$host);
  }
  $url = 'http://3.register.login.www.***.com/';
  $arr = parseHost($url);
  print_r($arr);
/*
X-Powered-By: PHP/5.2.0
Content-type: text/html

Array
(
    [0] => http://3.register.login.www.***.com/
    [1] => 3.register.login.www.***.com
    [2] => 3.register.login.www.
    [3] => baidu.
    [4] => com
)
Array
(
    [0] => 5
    [1] => baidu.com
    [2] => 3.register.login.www.***.com
)

  */

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值