-
PHP正则表达式匹配域名
- function matchdomain($q){
- preg_match('/(([a-z0-9](w|-){0,61}?[a-z0-9]|[a-z0-9]).){1,}(aero|arpa|asia|biz|cat|com|coop|co|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|[a-z][a-z])(.[a-z][a-z]){0,1}/', $q, $matches);
- return $matches[0];
- }
- //实例应用,代码如下:
- $com = 'www.zzbds.net';
- echo matchdomain($com);
- //www.zzbds.net
- $cn = 'afdsafs';
- echo matchdomain($cn);
- //notice: undefined offset: 0 因为没有不是域名所以正则不到域名所以出错了。
以下代码可以从URL中获得域名
例如:http://zzbds.net/html/database/ORACLE/69613.html
得到zzbds.net
function get_domain($url){
$pattern = "/[\w-]+\.(com|net|org|gov|cc|biz|info|cn)(\.(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","3322");//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;
}// end if(!strcmp...)
}// end if(count...)
}// end function