how to get URL host using php

前端 未结 2 493
借酒劲吻你
借酒劲吻你 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:23

    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

    0 讨论(0)
  • 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<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 
    
    0 讨论(0)
提交回复
热议问题