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

How to Extract Domain Names from Subdomains in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-22 08:07:30183browse

How to Extract Domain Names from Subdomains in PHP?

Extracting Domain Names from Subdomains in PHP

In contemporary web development, it is imperative to parse and retrieve domain names, even from their subdomains. A simple example may include domain names like "here.example.com" or "example.org". To address this need, we present a comprehensive PHP function designed to extract the root domain name from any given input.

Using a combination of PHP's native functions and regular expressions, this function comprehensively parses subdomains and returns the primary domain name. For instance, regardless of the input ("here.example.com", "example.org", or "here.example.org"), the function consistently returns the root domain, "example.org".

Within the function, the URL is parsed using PHP's parse_url() function, which decomposes the URL into its constituent components. The domain name is then extracted from the "host" key in the resulting array.

To further refine the domain name, a regular expression is employed. This pattern matches domain names consisting of alphanumeric characters and dashes. The expression captures the domain name and stores it in the domain group.

Finally, the function returns the extracted domain name, which represents the root domain of the input URL. The function effortlessly handles various domain formats, seamlessly accommodating different top-level domains (TLDs).

The above is the detailed content of How to Extract Domain Names 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
Previous article:Transactions in LaravelNext article:Transactions in Laravel