获取顶级域名修正版,parseHost() (更新日期2013-1-3)

2013-1-3 更新:

1,原先的其实有问题的。

2,不要迷信什么OOP,如果一个匹配出顶级域名的也非得写一个OOP出来,合适吗?PHP根本面向对象根本就不灵活!

3,PHP根本就不适合完全的面向对象!根本就不适合!


/**
 *  @access     public
 *  @param      string      $httpurl
 *  @return     array       [domainLevel,tophost,host,httpurl]
 */
function parseHost($httpurl)
{
    extract( parse_url($httpurl) );

    if(!(isset($scheme) && isset($host)))
    {
        return;
    }
    $dmtypeRegx = '/([a-z0-9\-]+\.)(com\.cn|org\.cn|net\.cn|com\.jp|co\.jp|com\.kr|com\.tw|cn|com|org|info|us|fr|de|tv|net|cc|biz|hk|jp|kr|name|me|tw|la)$/i';
    $tophost = preg_match($dmtypeRegx, $host, $matches) ? $matches[1].$matches[2]:'';
    if($tophost == $host || 'www.'.$tophost == $host)
    {
        $domainLevel = 1;
    } else {
        $domainLevel = substr_count(substr($host,0,strlen($host)-strlen($tophost)) , '.')+1;
    }
    $httpurl = $scheme.'://'.$host;
    if(isset($port) && !empty($port) && $port != 80)
    {
        $httpurl .= ':'.$port;
    }
    $httpurl = strtolower($httpurl);

    if(isset($path)) $httpurl .= $path;
    if(isset($query)) $httpurl .= '?'.$query;
    if(isset($fragment)) $httpurl .= '#'.$fragment ;

    return array($domainLevel,$tophost,$host,$httpurl);
}









--------------------------------------------------------------------------------------------------------------

2012-12-19补充:

1)最新的更新版在 http://blog.csdn.net/default7/article/details/8332612

2)第7行代码那个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[2] == 'www.' ? $host:$matches[3].$matches[4].$matches[5];
    return array($host,$tophost);
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值