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);
}
}