不能提取com.cn类似的域名:
<?php
$url = 'https://www.haiyun.me';
$host = parse_url($url, PHP_URL_HOST);
$host_parts = explode('.', $host);
$domain = implode('.', array_slice($host_parts, count($host_parts)-2));
echo $domain;
?>
<?php
$url = 'https://www.haiyun.me';
$host = parse_url($url, PHP_URL_HOST);
$host_parts = explode('.', $host);
if(count($host_parts) > 2) {
$host_parts = array_reverse($host_parts);
$domain = $host_parts[1].'.'.$host_parts[0];
} else {
$domain = $host;
}
echo $domain;
?>
正则,www.hai.me被认为是根域名:
<?php
function get_domain($url)
{
$domain = parse_url($url, PHP_URL_HOST);
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
var_dump($regs);
return $regs['domain'];
}
return false;
}
echo get_domain("https://www.haiyun.me");
?>
基于tld列表,精确:
https://publicsuffix.org/learn/