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

How to Extract Root Domain Names from Subdomains in PHP?

Linda Hamilton
Release: 2024-10-22 08:10:30
Original
513 people have browsed it

How to Extract Root Domain Names from Subdomains in PHP?

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

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:

<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

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:

<code class="php">print get_domain("http://somedomain.co.uk"); // outputs 'somedomain.co.uk'</code>
Copy after login

In cases where the URL does not conform to acceptable domain structures, the function gracefully handles these edge cases by returning false.

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