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.