PHPRO.ORG

Here is a function to perform the simple task of getting the domain name from a URL. The function requires a valid URL to work, and if an invalid URL, or a URL without a hostname and scheme is provide, the function will return false.


<?php

function getDomain($url)
{
    if(
filter_var($urlFILTER_VALIDATE_URLFILTER_FLAG_HOST_REQUIRED) === FALSE)
    {
        return 
false;
    }
    
/*** get the url parts ***/
    
$parts parse_url($url);
    
/*** return the host domain ***/
    
return $parts['scheme'].'://'.$parts['host'];
}
?>

Example Code


<?php

$url 
'http://phpro.org/classes/Phproogle-Docs.html';

echo 
getDomain($url);

?>