在 Web 開發中,從完整 URL 中精確提取頂級域名(如 jb51.net、baidu.com.cn)是常見需求。本文提供一個健壯的 PHP 函數,支援國際頂級域名(gTLD)與國家代碼頂級域名(ccTLD)的組合形式,並詳細解析其核心邏輯。
域名由多層組成,以 phpwind.com.cn 為例:
phpwindcomcn常見國際頂級域名包含:com、net、org、edu、gov、biz、info、me、cc、mobi 等;地域型域名通常為兩字母代碼,如 cn(中國)、tw(台灣)、hk(香港)。
function getdomain($url) {
$host = strtolower($url);
// 若傳入完整 URL,先解析出 host
if (strpos($host, '/') !== false) {
$parse = @parse_url($host);
$host = $parse['host'];
}
// 國際頂級域名資料庫
$topleveldomaindb = array(
'com', 'edu', 'gov', 'int', 'mil', 'net', 'org',
'biz', 'info', 'pro', 'name', 'museum', 'coop',
'aero', 'xxx', 'idv', 'mobi', 'cc', 'me'
);
// 建立正則模式:支援 "xxx.com"、"xxx.com.cn" 兩種形式
$str = implode('|', $topleveldomaindb);
$matchstr = "[^\.]+\.(?:(" . $str . ")|\w{2}|((" . $str . ")\.\w{2}))$";
if (preg_match("/" . $matchstr . "/ies", $host, $matchs)) {
$domain = $matchs[0];
} else {
$domain = $host; // 無法匹配時返回原 host
}
return $domain;
}
$str = "https://www.jb51.net/tools/zhengze.html";
echo getdomain($str); // 輸出:jb51.net
使用 parse_url() 自動提取 host 部分,兼容帶協議頭、路徑的完整 URL。
模式 [^\.]+\.(?:(gTLD列表)|\w{2}|((gTLD列表)\.\w{2}))$ 涵蓋三種情況:
example.com — 直接匹配國際頂級域名example.cn — 匹配兩字母國家代碼域名example.com.cn — 匹配「國際域名.國家代碼」雙層結構開頭使用 strtolower() 統一轉小寫,配合正則 i 修飾符,確保匹配不受大小寫影響。
.app、.dev、.ai),實際專案建議定期更新 $topleveldomaindb 陣列,或改用 Public Suffix List 等權威資料源。baidu.com 而非 map.baidu.com),需結合 Public Suffix List 做更精細判斷。這個函數結構清晰、邏輯完整,可直接用於專案中,也可作為進一步封裝域名解析類別的基礎。