How do you strip out the domain name from a URL in php?

后端 未结 9 1379
遥遥无期
遥遥无期 2020-12-02 22:12

Im looking for a method (or function) to strip out the domain.ext part of any URL thats fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .what

9条回答
  •  眼角桃花
    2020-12-02 22:52

    Here are a couple simple functions to get the root domain (example.com) from a normal or long domain (test.sub.domain.com) or url (http://www.example.com).

    /**
     * Get root domain from full domain
     * @param string $domain
     */
    public function getRootDomain($domain)
    {
        $domain = explode('.', $domain);
    
        $tld = array_pop($domain);
        $name = array_pop($domain);
    
        $domain = "$name.$tld";
    
        return $domain;
    }
    
    /**
     * Get domain name from url
     * @param string $url
     */
    public function getDomainFromUrl($url)
    {
        $domain = parse_url($url, PHP_URL_HOST);
        $domain = $this->getRootDomain($domain);
    
        return $domain;
    }
    

提交回复
热议问题