2

I need to know how to get the domain name from a url without the tld.

This is what I have that works for .com, .info, etc but not for .co.uk

// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i',
"http://example.co.uk", $matches);
$host = $matches[1];

// get last two segments of host name
preg_match('/([^.]+)\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[1]}\n";

When I get it to call "example.co.uk" domain it just shows: "co" when I need it to show "example"

Thanks

LionHeart
  • 65
  • 5

1 Answers1

1

Regex is falsy solution there, you need package that using Public Suffix List, only with it you can get correct result on complex TLDS.

I recomend TLDExtract for domain parsing, here is sample code that show diff:

$extract = new LayerShifter\TLDExtract\Extract();

# For 'http://www.domain.com/site'

$result = $extract->parse('http://www.domain.com/site');
$result->getFullHost(); // will return 'www.domain.com'
$result->getRegistrableDomain(); // will return 'domain.com'
$result->getSuffix(); // will return 'com'

# For 'http://www.domain.co.uk/site'

$result = $extract->parse('http://www.domain.co.uk/site');
$result->getFullHost(); // will return 'www.domain.co.uk'
$result->getRegistrableDomain(); // will return 'domain.co.uk'
$result->getSuffix(); // will return 'co.uk'
Oleksandr Fediashov
  • 4,315
  • 1
  • 24
  • 42