Extract domain out of URL
This is how you can extract a domain out of URL without the subdomains. The parse_url() function gives the domain with the subdomain and this function just take the last two pieces and return it put together.
<?php
function _get_domain($url) {
$host = parse_url($url, PHP_URL_HOST);
//If url is with out http, parse_url returns empty host
if (empty($host)) {
$host = $url;
}
$host = explode(".", $host);
return $host[count($host)-2] . "." . $host[count($host)-1];
}
?>
print _get_domain("http://www.example.com/aaa/bbb.php"); // => example.com
print _get_domain("http://www.example.com"); // => example.com
print _get_domain("www.example.com"); // => example.com
print _get_domain("example.com"); // => example.com
This is how the usual parse_url handle some URL:s
<?php
$url[] = "<a href="http://www.site.se";
">http://www.site.se";
</a>$url[] = "<a href="http://sub2.www.site.se";
">http://sub2.www.site.se";
</a>$url[] = "<a href="http://www.site.se/sv/index.php";
">http://www.site.se/sv/index.php";
</a>$url[] = "<a href="http://www.site.se/";
foreach">http://www.site.se/";
foreach</a> ($url as $key => $value) {
$parsed[] = parse_url($value);
}
foreach ($parsed as $key => $url) {
echo "<br>".$url['host'];
}
<a href="http://www.site.se
sub2.www.site.se
www.site.se
www.site.se
?>
sub2.www.site.se
www.site.se
www.site.se
?>
[/codefilter_code]