How to Extract Domain Names from Subdomains in PHP?

Patricia Arquette
Release: 2024-10-22 08:07:30
Original
182 people have browsed it

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!

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!