Home >Backend Development >PHP Tutorial >How to Retrieve Root Domain from Subdomains in PHP?

How to Retrieve Root Domain from Subdomains in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 08:08:30844browse

How to Retrieve Root Domain from Subdomains in PHP?

PHP: Extracting Root Domain from Subdomains

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 function assumes that all domains have a 3-letter Top-Level Domain (TLD).
  • The function handles both URLs and subdomains.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn