Extracting Domain Names from Subdomains in PHP
In PHP, obtaining the root domain name from a subdomain is a common task. Consider a scenario where you encounter variables like these:
here.example.com example.com example.org here.example.org
You aim to transform these values into their root domain names, such as example.com or example.org. To achieve this, a well-crafted function is required.
Solution
The following snippet demonstrates a function called get_domain() that effectively extracts the root domain name:
<code class="php">function get_domain($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; }</code>
This function utilizes the built-in parse_url() function to break down the URL and retrieve the host component. Subsequently, it employs a regular expression to validate and extract the root domain name, ensuring that it adheres to common domain naming conventions.
By calling get_domain() with the desired URL, you can effortlessly isolate the root domain name:
<code class="php">print get_domain("http://somedomain.co.uk"); // outputs 'somedomain.co.uk'</code>
In cases where the URL does not conform to acceptable domain structures, the function gracefully handles these edge cases by returning false.
The above is the detailed content of How to Extract Root Domain Names from Subdomains in PHP?. For more information, please follow other related articles on the PHP Chinese website!