Best Citizenships

PHP – How to get domain name from URL?

i was working on a recent project and suddenly i wanted to extract domain name domain.tld stripping off www or http://

I know that parse_url() is the function that accomplishes most of the task. I have tested this function and if users type with www.domain.com then domain.com is only available with path array variable and not in host array variable whereas with http:// the domain.com comes in host array. This is a tricky problem when parsing url to get domain and this function overcomes this

For example:

http://domain.co.uk => gives => domain.co.uk
http://domain.co.uk/users/main.html => gives => domain.co.uk
http://www.domain.co.uk => gives => domain.co.uk
www.domain.co.uk => gives => domain.co.uk

function GetDomain($url)
{
$nowww = ereg_replace('www\.','',$url);
$domain = parse_url($nowww);
if(!empty($domain["host"]))
	{
	 return $domain["host"];
	 } else
	 {
	 return $domain["path"];
	 }

}

The above function worked very well for me!

Method 2

Getting the domain name out of a URL using regular expressions. I accidentally found this code in php preg_match function

<?php
// get host name from URL
preg_match("/^(http:\/\/)?(&#91;^\/&#93;+)/i",
    "http://www.php.net/index.html", $matches);
$host = $matches&#91;2&#93;;

// get last two segments of host name
preg_match("/&#91;^\.\/&#93;+\.&#91;^\.\/&#93;+$/", $host, $matches);
echo "domain name is: {$matches&#91;0&#93;}\n";

/* Output is php.net */

?>  

Hope this helps!