Parsing domain from a URL

前端 未结 18 2202
独厮守ぢ
独厮守ぢ 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:36

    I have edited for you:

    function getHost($Address) { 
        $parseUrl = parse_url(trim($Address));
        $host = trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); 
    
        $parts = explode( '.', $host );
        $num_parts = count($parts);
    
        if ($parts[0] == "www") {
            for ($i=1; $i < $num_parts; $i++) { 
                $h .= $parts[$i] . '.';
            }
        }else {
            for ($i=0; $i < $num_parts; $i++) { 
                $h .= $parts[$i] . '.';
            }
        }
        return substr($h,0,-1);
    }
    

    All type url (www.domain.ltd, sub1.subn.domain.ltd will result to : domain.ltd.

提交回复
热议问题