Reputation: 2062
I've a string like third.second.tld
or fourth.third.second.tld
in php. What is the simplest and best way to extract the main domain name (second.tld)?
I tried this
$domain = 'fourth.third.second.tld';
$topLevel = array_reverse(explode('.', $domain))[0];
$secondLevel = array_reverse(explode('.', $domain))[1];
$mainDomain = $secondLevel . '.' . $topLevel;
but I think it's a bit complicated. Is there an easier way to do this?
Upvotes: 0
Views: 102
Reputation: 231
It is more complicated than you think - do use a library specifically built for such operations. Otherwise, you may discover the various pitfalls of different TLDs. For example, in .com-domains, the second level is usually the "main domain", but users in the UK are used to .co.uk-domains where the "main domain" is found at the 3rd level.
https://github.com/layershifter/TLDExtract is one of those libraries built for PHP and the README starts with an example to extract and split TLD, "main domain" and subdomains from each other. TLDExtract does also support IDNA-encoded domains (internationalized domain names).
Upvotes: 2
Reputation: 954
Or you could use regex
$a = 'fourth.third.second.tld';
$b = 'third.second.tld';
$c = 'second.tld';
function getDomainName($str) {
$r = preg_replace('/(\w*)(\.)(\w*)$/', '', $str);
return str_replace($r, '', $str);
}
echo getDomainName($a);
echo "\n";
echo getDomainName($b);
echo "\n";
echo getDomainName($c);
the result will be
second.tld
second.tld
second.tld
Upvotes: 1
Reputation: 79
$domain = 'fourth.third.second.tld';
$parts = explode(".", $domain);
$lastParts = array_slice($parts, -2);
$mainDomain = join(".", $lastParts);
//output: second.tld
Upvotes: 1