Home  >  Article  >  Backend Development  >  php中获取URL中域名的2个方法

php中获取URL中域名的2个方法

WBOY
WBOYOriginal
2016-06-20 13:03:131309browse

方法1:

自定义函数,好处是可以随时改写,不足是有些域名可能会解析不出

function get_domain($url)
{
$pattern = "/[/w-]+/.(com|net|org|gov|biz|com.tw|com.hk|com.ru|net.tw|net.hk|net.ru|info|cn|com.cn|net.cn|org.cn|gov.cn|mobi|name|sh|ac|la|travel|tm|us|cc|tv|jobs|asia|hn|lc|hk|bz|com.hk|ws|tel|io|tw|ac.cn|bj.cn|sh.cn|tj.cn|cq.cn|he.cn|sx.cn|nm.cn|ln.cn|jl.cn|hl.cn|js.cn|zj.cn|ah.cn|fj.cn|jx.cn|sd.cn|ha.cn|hb.cn|hn.cn|gd.cn|gx.cn|hi.cn|sc.cn|gz.cn|yn.cn|xz.cn|sn.cn|gs.cn|qh.cn|nx.cn|xj.cn|tw.cn|hk.cn|mo.cn|org.hk|is|edu|mil|au|jp|int|kr|de|vc|ag|in|me|edu.cn|co.kr|gd|vg|co.uk|be|sg|it|ro|com.mo)(/.(cn|hk))*/";
preg_match($pattern, $url, $matches);
if(count($matches) > 0)
{
return $matches[0];
}else{
$rs = parse_url($url);
$main_url = $rs["host"];
if(!strcmp(long2ip(sprintf("%u",ip2long($main_url))),$main_url))
{
return $main_url;
}else{
$arr = explode(".",$main_url);
$count=count($arr);
$endArr = array("com","net","org");//com.cn net.cn 等情况
if (in_array($arr[$count-2],$endArr))
{
$domain = $arr[$count-3].".".$arr[$count-2].".".$arr[$count-1];
}else{
$domain = $arr[$count-2].".".$arr[$count-1];
}
return $domain;
}
}
}

方法2:

用自带函数,好处是使用方便,我现在使用的就是这个

如果你不想要www,可以用str_replace替换掉

$Url='http://www.scutephp.com/index.html';
$tempu=parse_url($Url);
$message=$tempu['host'];
echo $message;
//输出结果就是 www.scutephp.com

 


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn