Home >Backend Development >PHP Tutorial >How to Retrieve a URL\'s Subdomain Using PHP?

How to Retrieve a URL\'s Subdomain Using PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 14:10:14265browse

How to Retrieve a URL's Subdomain Using PHP?

Retrieve the Subdomain of a URL Using PHP Function

To obtain the subdomain portion of a URL, PHP offers a convenient function. Let's explore this function and provide a solution to your query.

Function to Get Subdomain

The explode() function in PHP can be utilized to split a string into an array based on a specified delimiter. To extract the subdomain from a URL, we can split the hostname using dots as the delimiter.

Solution

Here's a straightforward solution:

$subdomain = array_shift(explode('.', 'en.example.com'));

This code assigns the "en" portion of the URL to the $subdomain variable.

Alternative Approach (PHP 5.4 onwards)

Starting from PHP version 5.4, you can use a simplified approach:

$subdomain = explode('.', 'en.example.com')[0];

Both approaches accomplish the same objective: extracting the subdomain from the given URL.

The above is the detailed content of How to Retrieve a URL\'s Subdomain Using 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