how to get URL host using php

前端 未结 2 492
借酒劲吻你
借酒劲吻你 2020-12-22 02:55

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 on

2条回答
  •  天命终不由人
    2020-12-22 03:26

    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[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 
    

提交回复
热议问题