February 28th in PHP Scripts by pbu .

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:

Share and Enjoy:
  • del.icio.us
  • digg
  • StumbleUpon
  • Technorati
  • DZone
  • Facebook
  • FriendFeed
  • Reddit
  • RSS
  • Twitter

7 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

Leave A Comment.