Parsing domain from a URL

前端 未结 18 2184
独厮守ぢ
独厮守ぢ 2020-11-22 12:26

I need to build a function which parses the domain from a URL.

So, with

http://google.com/dhasjkdas/sadsdds/sdda/sdads.html

or

18条回答
  •  既然无缘
    2020-11-22 12:34

    From http://us3.php.net/manual/en/function.parse-url.php#93983

    for some odd reason, parse_url returns the host (ex. example.com) as the path when no scheme is provided in the input url. So I've written a quick function to get the real host:

    function getHost($Address) { 
       $parseUrl = parse_url(trim($Address)); 
       return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); 
    } 
    
    getHost("example.com"); // Gives example.com 
    getHost("http://example.com"); // Gives example.com 
    getHost("www.example.com"); // Gives www.example.com 
    getHost("http://example.com/xyz"); // Gives example.com 
    

提交回复
热议问题