How to get domain name from URL in PHP

How to get domain name from URL in PHP

Parse domain name from URL is used in many cases within the web project. During this short tutorial, we’ll provide an easy code snippet to get domain name from URL in PHP. Using our example script, you’ll be ready to extract only the domain name from any type of URL.

All PHP code are group together in getdomain() function. The $url param should be passed to getdomain() function, from which you would like to get the name . Getdomain() function returns the name if found and FALSE if not found.

Function getdomain($url){
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
If(preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)){
Return $regs['domain'];
}
Return FALSE;
}

Echo getdomain("http://example.com"); // outputs 'example.com'
Echo getdomain("http://www.example.com"); // outputs 'example.com'
Echo getdomain("http://mail.example.co.uk"); // outputs 'example.co.uk'

Praveen Kumar

I am a fullstack web developer with a passion for SEO, creating stunning websites, and organic marketing. I am a perfectionist.

Post navigation