Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 783
charlie Avatar asked Sep 27 '22 19:09

charlie


2 Answers

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.

like image 145
Ali Gajani Avatar answered Oct 03 '22 01:10

Ali Gajani


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

like image 28
danish farhaj Avatar answered Oct 03 '22 01:10

danish farhaj