How to Get Domain Name from URL in PHP
Last Update : 23 Jan, 2023In this article, you will learn to get a domain name included in the provided URL.
When you developing a web project, Sometimes you need to get the domain name from the URL. Here, provides provide a simple code snippet to get a domain name from the URL in PHP. You can extract only the domain name from any type of URL using the following example script.
For this, first, you need to make a function of getDomainFromURL() to group together all the PHP code. getDomainFromURL() function required a $url as a parameter. The $url parameter includes the provided URL for which you want to get the domain name.
Also, the getDomainFromURL() function returns the domain name when it is found and returns FALSE when it is not found.
function getDomainFromURL($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 getDomainFromURL("http://example.com");
echo getDomainFromURL("http://www.example.com");
echo getDomainFromURL("http://ads.example.co.uk");
This program produces the following result -:
example.com
example.com
example.co.uk