Home > Backend Development > PHP Tutorial > How Can I Extract the Subdomain from a URL in PHP?

How Can I Extract the Subdomain from a URL in PHP?

Susan Sarandon
Release: 2024-12-04 09:49:10
Original
325 people have browsed it

How Can I Extract the Subdomain from a URL in PHP?

Retrieving the Subdomain from a URL in PHP

When working with URLs, it's often necessary to extract specific parts such as the subdomain. In PHP, you can achieve this effortlessly using a built-in function.

Solution

To obtain the subdomain of a URL, you can leverage the following code:

array_shift((explode('.', $_SERVER['HTTP_HOST'])));
Copy after login

This function effectively separates the parts of the domain into an array using the dot (.) as the delimiter. The "array_shift" function then retrieves the first element of the array, which represents the subdomain.

For example, given the URL "en.example.com", the code will extract the "en" portion.

Alternative Syntax

In PHP 5.4 and later, you can utilize a more concise syntax to achieve the same result:

explode('.', 'en.example.com')[0];
Copy after login

This syntax simplifies the process by directly indexing the resulting array.

The above is the detailed content of How Can I Extract the Subdomain from a URL in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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