When working with domain names, it's often necessary to separate the root domain from any subdomains. Consider a variable containing various domain structures:
here.example.com example.com example.org here.example.org
Our task is to create a function that converts all of these variations into their corresponding root domains, such as "example.com" or "example.org." Here's how:
<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>
Explanation:
The pattern ensures that the domain consists of:
Example Usage:
<code class="php">echo get_domain("http://somedomain.co.uk"); // Outputs 'somedomain.co.uk'</code>
The above is the detailed content of How to Extract Root Domain from Subdomains in PHP?. For more information, please follow other related articles on the PHP Chinese website!