Home >Backend Development >PHP Tutorial >How to Retrieve Root Domain from Subdomains in PHP?
Query:
How do I retrieve the root domain name from a given subdomain using PHP?
Solution:
The following PHP function can be used to parse and extract the root domain name from a given URL or subdomain:
<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>
Example:
To retrieve the root domain name from a given subdomain, simply pass the subdomain as an argument to the function:
<code class="php">print get_domain("here.example.com"); // outputs 'example.com'</code>
Additional Considerations:
The above is the detailed content of How to Retrieve Root Domain from Subdomains in PHP?. For more information, please follow other related articles on the PHP Chinese website!