How to Get Domain Name from URL in PHP
Parse domain name from URL is used in many cases in the web project. In this short tutorial, we’ll provide a simple code snippet to get domain name from URL in PHP. Using our example script, you’ll be able 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 want to get the domain name. getDomain()
function returns the domain name if found and FALSE if not found.<?php
function get_domain($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://www.example.com"); // outputs 'example.com'
echo get_domain("http://mail.somedomain.co.uk"); // outputs 'somedomain.co.uk'
echo getDomain("http://example.com"); // outputs 'example.com'
?>
COMMENTS