在 PHP 中获取顶级域名(Top-Level Domain,TLD)可以通过多种方法实现。以下是一些常见的方法和相关概念:
.com
、.org
、.net
等。example.com
中的 example
。parse_url
和 explode
function getTopLevelDomain($url) {
$parsedUrl = parse_url($url);
if (!isset($parsedUrl['host'])) {
return null;
}
$hostParts = explode('.', $parsedUrl['host']);
$tld = '.' . end($hostParts);
return $tld;
}
$url = "https://www.example.com/path";
echo getTopLevelDomain($url); // 输出: .com
gethostbyaddr
和 explode
function getTopLevelDomainByIp($ip) {
$host = gethostbyaddr($ip);
if (!$host) {
return null;
}
$hostParts = explode('.', $host);
$tld = '.' . end($hostParts);
return $tld;
}
$ip = "93.184.216.34"; // example.com 的 IP 地址
echo getTopLevelDomainByIp($ip); // 输出: .com
tld-extract
tld-extract
是一个专门用于提取域名的库,可以更准确地处理各种情况。
require 'vendor/autoload.php';
use TldExtract\Extract;
$extract = new Extract();
$result = $extract->parse('http://www.example.co.uk/path');
echo $result->getTld(); // 输出: co.uk
tld-extract
可以更准确地处理各种复杂的域名情况。idn_to_ascii
函数进行转换。idn_to_ascii
函数进行转换。通过以上方法,你可以在 PHP 中有效地获取顶级域名,并根据具体需求选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云