How To Get Domain Name From Subdomain in PHP Tutorial

Table of Contents

Share this Article
Reading Time: 2 minutes
270 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.

Examples

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

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

Learn More –

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.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Was this post helpful?

PHP Web Development Courses on Offer in just $4
PHP Web Development Courses on Offer in just $4