5

How can i return just the TLD of a domain name

for example, if i had the following:

www.domain.co.uk i want to return just the .co.uk

and the same for domain.co.uk

and the same for all other TLDs (.com, .co, .org etc)

Is there an easy way to do this in PHP without using Regex

I was thinking of using explode but im not too familiar with that

3
  • 1
    it will not help. @MangeshSatheIND Commented May 29, 2015 at 11:05
  • parse_url will give you domain name & then performing regular expression on it, you can get expected .com /.co.uk etc.. Commented May 29, 2015 at 11:11
  • OP already have domain name Commented May 29, 2015 at 11:14

4 Answers 4

2

You can use a library called tldextract.php.

Find it here https://github.com/data-ac-uk/equipment/blob/master/_misc/tldextract.php

Usage is very simple:

$extract = new TLDExtract();
$components = $extract('http://forums.bbc.co.uk/');
echo $components['tld']; // co.uk

Now how simple was that?

If you read the code, you can see that it uses a large list of tlds in the fetchTldList() function.

Sign up to request clarification or add additional context in comments.

1 Comment

While this answer (in the background) is utilizing regex, the provided resource (publicsuffix.org) is incredibly helpful! +1
1
$returnHostName = parse_url($url, PHP_URL_HOST) //it will retrun 'domain' in your case
$returnArrayType = explode($returnHostName, $returnHostName); //explode it from string 'domain'

Okay now the variable returnArrayType contain your desired output but in the form of array you can get it from calling it's index.

check if It will work.

Comments

1

Not regex, not parse_url() will not help you.

You need library that extacts TLD using Public Suffix List, I recomend to use TLDExtract.

Comments

0

This function work to www and not-www domain name. Not working to subdomains. For better results you need to use a regex or a library.

    $domain = "www.domain.co.uk";
    function tld($domain)
    {
        if (strstr('www', $domain)) {
            $part = 3;
        } else {
            $part = 2;
        }
        $expld = explode('.', $domain);
        if (count($expld) > $part) {
            return $expld[count($expld) - 2] . '.' . $expld[count($expld) - 1];
        } else {
            return $expld[count($expld) - 1];
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.