Search code examples
phpurlparse-url

How to get only center domain name from url


I have many thousands of urls from which i only want to get name of domain for example

http://google.com

<?php

$url = 'http://google.com';
$host = parse_url($url);
echo '<pre>';
print_r($host['host']);
echo '</pre>';

**//Output google.com**

?>

but i only want to get google from http://google.com not google.com

please help thanks


Solution

  • Not particularaly elegant but something like this gets simply the domain name...

    $url = 'http://dev.subdomain.google.com';
    $host = parse_url($url,PHP_URL_HOST);
    $pieces=explode( '.', $host );
    $popped=array_pop( $pieces ); //remove tld extension from stack
    if( strlen( $popped ) <= 3 ) array_pop( $pieces ); //tld was likely a multi-part ext like .co.uk so pop next element off stack too!
    
    $domain=array_pop( $pieces );
    
    echo $domain; // returns 'google'