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 then is only available with path array variable and not in host array variable whereas with http:// the comes in host array. This is a tricky problem when parsing url to get domain and this function overcomes this

For example: => gives => => gives => => gives => => gives =>

function GetDomain($url)
$nowww = ereg_replace('www\.','',$url);
$domain = parse_url($nowww);
	 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

// get host name from URL
    "", $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 */


Hope this helps!