February 28th in PHP Scripts by .

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:\/\/)?([^\/]+)/i",
    "http://www.php.net/index.html", $matches);
$host = $matches[2];

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

/* Output is php.net */

?>

Hope this helps!

Similar Posts:

19 Comments

  • Austin
    March 5, 2009
  • Austin
    March 5, 2009
  • yudi
    June 23, 2009
  • yudi
    June 23, 2009
  • IDENTA
    April 28, 2010
  • Madeline Morgan
    May 19, 2010
  • Australia Betting Sites
    November 24, 2010
    • Maneesh
      January 9, 2011
  • Gareth
    February 2, 2011
  • supernova
    March 25, 2011
  • John Lam
    April 25, 2011
  • R4 R4i
    May 5, 2011
  • R4
    June 17, 2011
  • r4i
    June 20, 2011
  • Guillaume
    August 9, 2011
  • tired
    August 13, 2011
  • peak
    December 13, 2011
  • Evgen
    February 1, 2012

Leave A Comment.