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!