How to Retrieve Root Domain from Subdomains in PHP?

Mary-Kate Olsen
Release: 2024-10-22 08:08:30
Original
749 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!