user1956779 user1956779 - 5 months ago 24
PHP Question

PHP Finding a domain name and domain extension from an array

I have an array of data containing some domains with TLD extensions. I want to collect the domain name and TLD extension seperately.

E.g. From "hello.com" I want to collect "hello" as one variable, and then collect ".com" as another variable.

Another E.g. IMPORTANT, from "hello.co.uk" I want to collect "hello" as one variable, and then collect ".co.uk" as another variable.

My current code using pathinfo() will work correctly on "hello.com", but not "hello.co.uk". For "hello.co.uk" it will collect "hello.co" as one variable, and then collect ".uk" as another variable.

Here is the code I am using:

// Get a file into an array
$lines = file($_FILES['file']['tmp_name']);

// Loop through array
foreach ($lines as $line_num => $line) {
echo $line;

//Find TLD
$tld = ".".pathinfo($line, PATHINFO_EXTENSION);
echo $tld;

//Find Domain
$domain = pathinfo($line, PATHINFO_FILENAME);
echo $domain;
}


Hopefully I explained that well enough.
I use stackoverflow a lot but couldn't find a specific example of this.

Thanks

Taz Taz
Answer

Instead of using functions intended for files, you could just use some simple string manipulation:

$domain = substr($line, 0, strpos($line, "."));
$tld = substr($line, strpos($line, "."), (strlen($line) - strlen($domain)));