获取没有 TLD 的域名

sg5*_*552 3 php preg-match

我这里有这个代码:

    // get host name from URL
    preg_match('@^(?:http://)?([^/]+)@i',
    "http://www.joomla.subdomain.php.net/index.html", $matches);
    $host = $matches[1];

    // get last two segments of host name
    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
    echo "domain name is: {$matches[0]}\n";
Run Code Online (Sandbox Code Playgroud)

输出将是 php.net

我只需要php没有.net

Bai*_*ker 5

虽然正则表达式在这里很好,但我建议 parse_url

$host = parse_url('http://www.joomla.subdomain.php.net/index.html', PHP_URL_HOST);
$domains = explode('.', $host);
echo $domains[count($domains)-2];
Run Code Online (Sandbox Code Playgroud)

这适用于 .com、.org、.net 等 TLD,但不适用于 .co.uk 或 .com.mx。您需要更多的逻辑(很可能是一组 tld)来解析它们。