In PHP, extracting the root domain name from a subdomain is a common task. This is useful when you need to identify the main website associated with a subdomain. To accomplish this, let's explore a solution.
The provided code snippet leverages the parse_url function to break down the URL into its components, including the domain name. Subsequently, it employs a regular expression to isolate the root domain, disregarding the subdomain.
The following example illustrates the usage of this function:
print get_domain("http://here.example.com"); // outputs 'example.com'
function get_domain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
}
return false;
}
This function effectively extracts the root domain name from any URL, whether it contains a subdomain or not. By applying this technique, you can reliably identify the primary domain associated with any subdomain.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3