Home  >  Article  >  Backend Development  >  How to Extract Root Domain from Subdomains in PHP?

How to Extract Root Domain from Subdomains in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 08:13:30170browse

How to Extract Root Domain from Subdomains in PHP?

PHP: Extracting Root Domain from Subdomains

When working with domain names, it's often necessary to separate the root domain from any subdomains. Consider a variable containing various domain structures:

here.example.com
example.com
example.org
here.example.org

Our task is to create a function that converts all of these variations into their corresponding root domains, such as "example.com" or "example.org." Here's how:

Solution using Regular Expression

<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>

Explanation:

  • parse_url() breaks down the URL into its components, including the domain name.
  • Regular expression extracts only the root domain using a capture group ((?P...))).
  • The pattern ensures that the domain consists of:

    • Alphanumeric characters or hyphens
    • Maximum length of 63 characters for the subdomain
    • 2-6 character extension (TLD) separated by a dot

Example Usage:

<code class="php">echo get_domain("http://somedomain.co.uk"); // Outputs 'somedomain.co.uk'</code>

The above is the detailed content of How to Extract 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