Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

php - Getting domain name without TLD

I have this code right here:

    // 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]}
";

The output will be php.net

I need just php without .net

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Although regexes are fine here, I'd recommend parse_url

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

This will work for TLD's like .com, .org, .net, etc. but not for .co.uk or .com.mx. You'd need some more logic (most likely an array of tld's) to parse those out .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...