Get domain from URL in PHP
- How to Get the Domain from a URL in PHP
- Using parse_url() (Recommended)
- Removing Subdomains to Get the Root Domain
- Using Regular Expressions (Quick but Limited)
How to Get the Domain from a URL in PHP
Extracting a domain from a URL is a common need in PHP, whether you’re validating inputs, filtering analytics data, or handling redirects. PHP provides several reliable ways to do this, from built-in functions to regular expressions. This guide explains all the practical approaches, including how to remove subdomains when necessary.
Using parse_url() (Recommended)
The simplest and most reliable method is to use PHP’s built-in parse_url() function, which breaks a URL into its components.
Example:
<?php$url = 'https://blog.example.co.uk/article?id=10'; $host = parse_url($url, PHP_URL_HOST);echo $host; // Output: blog.example.co.uk
This retrieves the full host (including subdomains). It’s ideal for general use cases where you need the entire hostname.
Removing Subdomains to Get the Root Domain
When you only need the root domain (for example, example.co.uk instead of blog.example.co.uk), you can split the host and extract the last two or three parts intelligently.
Example:
<?php$url = 'https://blog.example.co.uk';$host = parse_url($url, PHP_URL_HOST); $parts = explode('.', $host);$count = count($parts); if ($count > 2) { $domain = $parts[$count - 2] . '.' . $parts[$count - 1];} else { $domain = $host;} echo $domain; // Output: example.co.uk
This works well for most standard domain structures, though country-code TLDs (like .co.uk, .com.au) may need extra handling depending on your requirements.
Using Regular Expressions (Quick but Limited)
You can also use a regex for simple extraction, though it’s not as reliable for complex domains.
Example:
<?php$url = 'https://store.blog.example.com/path';preg_match('/^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)/', $url, $matches); echo $matches[1]; // Output: store.blog.example.com
You can further process $matches[1] using the earlier subdomain-removal logic to isolate the root domain.
Stay Updated.
I'll you email you as soon as new, fresh content is published.
Latest Posts