-3

I search in internet and i found this code for find domain name

function get_domain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) 
{
return $regs['domain'];
}
return false;
}

Its works for http://www.google.com or http://www.google.co.uk

But its not working for test.web.tv.

Anybody can help me ?

How i can find min domain ?

Thanks

JefClaes
  • 3,275
  • 21
  • 23

1 Answers1

1

The function parse_url() requires a valid URL. In this case test.web.tv isn't valid, so parse_url() won't give you the expected results. In order to get around this, you could first check if the URL has the http:// prefix, and if it doesn't, manually prepend it. That way, you can get around the limitation of parse_url().

However, I think it'd be better to use the following function.

function getDomain($url) 
{    
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }

    $domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
    return $domain;
}

Explanation:

  • The given URL's passed to parse_url() with the PHP_URL_HOST flag and the full host is obtained
  • It's exploded with . as a delimiter
  • The last two pieces of the array is sliced -- ie. the domain name
  • It's joined back using implode()

Test:

echo getDomain('test.web.tv');

Output:

web.tv

Demo!

Note: It's a modified version of my own answer here combined with Alix's answer here.

This function currently doesn't work for .co.uk domain extensions -- you can easily add a check and change the array_slice function accordingly.

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150