How to Extract Root Domain from Subdomains in PHP?

Barbara Streisand
Release: 2024-10-22 08:13:30
Original
166 people have browsed it

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

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

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

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!

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!