1

I want to get the domain extension from the url. eg. .com, .net etc.

I have used this:

$extension = pathinfo($_SERVER['SERVER_NAME'], PATHINFO_EXTENSION);

I was just wondering if there was a better way using parse_url?

user1794021
  • 373
  • 3
  • 5
  • 9

2 Answers2

10

Use parse_url(). Something like:

$host = parse_url('http://www.google.co.uk/test.html');
preg_match('/(.*?)((\.co)?.[a-z]{2,4})$/i', $host['host'], $m);

$ext = isset($m[2]) ? $m[2]: '';

Edit: Fixed with regex from this answer. Extension like .co.uk are supported too.

Community
  • 1
  • 1
Nadh
  • 6,987
  • 2
  • 21
  • 21
-3

You can easily split the requested URI like this:

function tld( $uri ) {
    $parts = explode('.', $uri);

    return (sizeof($parts) ? ('.' . end($parts)) : false;
}

So you can do this:

if(!tld('googlecom')) // does not contain an ending TLD

if(tld('google.com')) // this is a valid domain name; output: ".com"

Or you can just use:

echo $_SERVER['SERVER_NAME'];

So in my oppinion the most best example of usage is:

echo tld($_SERVER['SERVER_NAME']);