How To Get Domain Name From Subdomain in PHP Tutorial

Reading Time: 2 minutes
910 Views

Inside this article we will see the concept i.e How To Get Domain Name From Subdomain in PHP Tutorial. Article contains the classified information about PHP Getting Domain Name From Subdomain.

If you are looking for a solution i.e PHP function to get the domain name from subdomain then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.

Read More: CodeIgniter 4 How to Insert Multiple Records Example Tutorial

Examples

Subdomain: https://api.onlinewebtutorblog.com
Domain: onlinewebtutorblog.com

Subdomain: https://tools.onlinewebtutorblog.com
Domain: onlinewebtutorblog.com

Let’s get started.

Application Programming

Create a folder say filter-domain in your localhost directory. Create a file index.php into it.

<?php

// Get domain name from subdomain
// Example: https://example.domain.com =>  domain.com

if (!function_exists('get_domain_from_subdomain')) {

    function get_domain_from_subdomain($subdomain)
    {
        $pieces = parse_url($subdomain);
        $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 get_domain_from_subdomain("https://api.onlinewebtutorblog.com");

Concept

We used PHP functions parse_url() and preg_match() with regex pattern to remove https://, www., etc.

Output

onlinewebtutorblog.com

We hope this article helped you to learn How To Get Domain Name From Subdomain in PHP Tutorial in a very detailed way.

Read More: Laravel 9 How to Insert Multiple Records Example Tutorial

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.