Getting TLD from domain input

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
evilcoder
Forum Contributor
Posts: 345
Joined: Tue Dec 17, 2002 5:37 am
Location: Sydney, Australia

Getting TLD from domain input

Post by evilcoder »

Hey guys, how would i extract a 3 letter TLD from a string?
eg:

$domain = "somesite.net";

i want to be able to separate this string into 2 variables:

$host & $tld

Thanks guys. :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

preg_match('|^(.*)\.([^.]{2,})$|',$domain,$matches);

print_r($matches);
I think...
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post by kettle_drum »

explode(".", $domain); then take the last item in the array, check to see if its 3 letters, if its 2 take the one before as well so you can get stuff like .com/.org/co.uk/.org.uk etc
evilcoder
Forum Contributor
Posts: 345
Joined: Tue Dec 17, 2002 5:37 am
Location: Sydney, Australia

Post by evilcoder »

Thanks guys, i ended up using kettle's solution and added count.

Code: Select all

<?php

$domain = "strip.com.au";
$lines = explode(".", $domain);
$count = sizeof ( $lines );
echo $lines[1] . "." . $lines[2];
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

wouldn't it be more like:

Code: Select all

<?php

$domain = "strip.com.au";

$domains = explode('.',$domain);

if(strlen($domains[sizeof($domains) - 1]) == 2)
{
  $tld = $domains[sizeof($domains) - 2].'.'.$domains[sizeof($domains) - 1];
}
else
{
  $tld = $domains[sizeof($domains) - 1];
}
?>
evilcoder
Forum Contributor
Posts: 345
Joined: Tue Dec 17, 2002 5:37 am
Location: Sydney, Australia

Post by evilcoder »

Yeah, thats better. Thanks mate.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

should probably toss a sanity check in there two.. (for at least 1 dot..) :)
Post Reply