Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting domain name without TLD

Tags:

php

preg-match

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

The output will be php.net

I need just php without .net

like image 541
sg552 Avatar asked Oct 20 '25 17:10

sg552


1 Answers

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 .

like image 62
Bailey Parker Avatar answered Oct 23 '25 05:10

Bailey Parker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!