2

I would like to get the host name of any url for example if i've the following url

$url = "http://www.google.com";

then i want to get only google what is after dot . and before extension dot . so that it can be applied for all types of urls.

so the results should be google ! i think this might needs regex or somehow any idea how to do it , Thanks.

Reham Fahmy
  • 4,937
  • 15
  • 50
  • 71

2 Answers2

8

You can try

echo __extractName("http://google.com"); 
echo __extractName("http://office1.dept1.google.com");
echo __extractName("http://google.co.uk");


function __extractName($url)
{
  $domain = parse_url($url , PHP_URL_HOST);
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $list)) {
    return substr($list['domain'], 0,strpos($list['domain'], "."));
  }
  return false;
}

Output

google
google 
google 
Baba
  • 94,024
  • 28
  • 166
  • 217
2

You should have a look at PHP's parse_url() function which returns an associative array of the various components that constitute a URL.

$url = "http://www.google.com";
print_r(parse_url($url)); 

Will echo the following array.

Array ( [scheme] => http [host] => www.google.com ) 

The above function will just give you a start. Check into the following Stackoverflow archives on how to take it up from here.

PHP Getting Domain Name From Subdomain

Get domain name (not subdomain) in php

PHP function to get the subdomain of a URL

EDIT (few more archives - I'm not sure what you googled/tried)

how to get domain name from URL

Extract Scheme and Host from HTTP_REFERER

Community
  • 1
  • 1
verisimilitude
  • 5,077
  • 3
  • 30
  • 35
  • Note that you can also pass `PHP_URL_HOST` as the second parameter, and it will just return the hostname instead of an array. – Waleed Khan Oct 02 '12 at 11:31
  • well based on your idea and very amazing archives, i will use 'explode' and then will results an array where i can print only the exact part of url i want. ~ thanks – Reham Fahmy Oct 02 '12 at 11:34
  • for sure. Next time around, ensure that you "google" :) Lest you'll either be downvoted or your question will be closed. – verisimilitude Oct 02 '12 at 11:36