php怎么获取域名中的顶级域名
墨初 编程开发 433阅读
下面博文中提供两个利用php脚本从一个网址中获取顶级域名的方法函数,大家可以做个参考。
php获取域名中顶级域名的方法
方法1:
下面为一个自定义的php函数,用于获取网址中的顶级域名
/** * @name 获取指定网址中顶级域名 * @param string $url 需要处理的网址 * * @return string 网址中的顶级域名 * @host 73so.com */ function getdomain($url) { $host = strtolower($url); if(strpos ( $host, '/' ) !== false) { $parse = @parse_url ( $host ); $host = $parse ['host']; } //网上收集的,有可以不全,可自行进行补充 $topleveldomaindb = array("top","wang","shop","xyz","kim","vip","ren","cc","xin","site","biz","auto","link","cn","club","net","info","ink","ltd","mobi","pro","red","org","com","group","comcn","netcn","orgcn","fun","online","store","tech","work","run","gold","life","fund","city","world","cool","company","zone","today","chat","show","email","plus","center","team","live","pub","video","social","co","love","icu","art","中国","网店","佛山","广东","公司","集团","我爱你","商标","网络","网址","信息","中文网","在线"); $str = ''; foreach($topleveldomaindb as $v ) { $str .= ($str ? '|' : '') . $v; } $matchstr = "[^\.]+\.(?:(".$str.")|\w{2}|((".$str.")\.\w{2}))$"; if (preg_match ( "/".$matchstr."/is",$host,$matchs)) { $domain = $matchs ['0']; } else { $domain = $host; } return $domain; } echo getdomain('https://www.73so.com/'); // 73so.com echo getdomain('https://www.73so.com/art/78.html'); // 73so.com
方法2:
下面提供的php获取网址中顶级域名的方法要比方法1中的示例简单的多,但也要对双拼后缀的域名做一下单独的处理。
/** * @name 获取指定网址中顶级域名 * @param string $url 需要处理的网址 * * @return string 网址中的顶级域名 * @host 73so.com */ function getTopHost($url) { $url = strtolower($url); $hosts = parse_url($url); $host = $hosts['host']; $data = explode('.', $host); $n = count($data); $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/'; if (($n > 2) && preg_match($preg, $host)) { $host = $data[$n - 3] . '.' . $data[$n - 2] . '.' . $data[$n - 1]; } else { $host = $data[$n - 2] . '.' . $data[$n - 1]; } return $host; } echo getTopHost('https://www.73so.com/'); // 73so.com echo getTopHost('https://www.73so.com/art/78.html'); // 73so.com