"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Extract Domain Names from Subdomains in PHP?

How to Extract Domain Names from Subdomains in PHP?

Published on 2024-11-08
Browse:802

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

Release Statement This article is reprinted at: 1729555520 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3