Search code examples
phppreg-replaceparse-url

parse_url and removing subdomain


I'm wanting to strip out everything from a URL but the domain. So https://i.sstatic.net/inhSc.jpg becomes imgur.com.

$url = 'https://i.sstatic.net/inhSc.jpg';

$parsedurl = parse_url($url);

$parsedurl = preg_replace('#^www\.(.+\.)#i', '$1', $parsedurl['host']);

// now if a dot exists, grab everything after it. This removes any potential subdomain
$parsedurl = preg_replace("/^(.*?)\.(.*)$/","$2",$parsedurl);

The above works but I feel like I should only being one preg_replace for this. Any idea how I may combine the two?


Solution

  • You can use parse_url() to get desired output like this,

        $url = "http://i.imgur.com/rA81kQf.jpg";
        $parseData = parse_url($url);
        $domain = preg_replace('/^www\./', '', $parseData['host']);
    
    
        $array = explode(".", $domain);
    
        echo (array_key_exists(count($array) - 2, $array) ? $array[count($array) - 2] : "") . "." . $array[count($array) - 1];
    

    which prints

    imgur.com