charlie
charlie

Reputation: 481

Split PHP String of a URL

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

Upvotes: 5

Views: 207

Answers (4)

Oleksandr Fediashov
Oleksandr Fediashov

Reputation: 4335

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

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

Upvotes: 1

ZI TEG
ZI TEG

Reputation: 63

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

Upvotes: 0

Ali Gajani
Ali Gajani

Reputation: 15091

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.

Upvotes: 2

danish farhaj
danish farhaj

Reputation: 1354

$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.

Upvotes: 1

Related Questions