free stats

How to Get Domain Name from URL in PHP

Last Update : 23 Jan, 2023 How to Guide in PHP

In 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("");
echo getDomainFromURL("");
echo getDomainFromURL("");

This program produces the following result -:


You found this tutorial / article valuable? Need to show your appreciation? Here are some options:

01. Spread the word! Use following buttons to share this tutorial / article link on your favorite social media sites.

02. Follow us on Twitter, GitHub ,and Facebook.