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:
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 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:
print get_domain("http://somedomain.co.uk"); // outputs 'somedomain.co.uk'
In cases where the URL does not conform to acceptable domain structures, the function gracefully handles these edge cases by returning false.
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