how to get URL host using php

2020-02-15 05:44发布

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.

标签: php regex url
2条回答
Summer. ? 凉城
2楼-- · 2020-02-15 06:09

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

查看更多
欢心
3楼-- · 2020-02-15 06:10

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 
查看更多
登录 后发表回答