mtownsend
11/15/2018 - 8:57 PM

url_to_domain

Extract the domain name from a url

<?php

if (!function_exists('url_to_domain')) {
    /**
     * Take a URL and parse it to return the domain name
     *
     * @param (string) $url
     * @return mixed string or false if url cannot be parsed
     *
     */
    function url_to_domain($url)
    {
        $domain = @parse_url($url, PHP_URL_HOST);
        if (!$domain) {
            return false;
        }

        // Check for subdomain and eliminate
        if (substr_count(strtoupper($domain), '.') > 1) {
            $subdomain = explode('.', $domain)[0];
            $domain = str_replace("$subdomain.", '', $domain);
        }

        return $domain;
    }
}