Home >Backend Development >PHP Tutorial >How Can I Extract a Subdomain from a URL in PHP?
Retrieving Subdomain from URL in PHP
Identifying the subdomain within a URL can be a common task in various web applications. This article explores PHP's functionality for extracting the subdomain from a given URL.
Function to Extract Subdomain
PHP doesn't provide a built-in function to retrieve the subdomain. However, there's a simple workaround using the array_shift() and explode() functions:
function getSubdomain($url) { // Split the URL into its components $parts = explode('.', $url); // Remove the top-level domain (e.g., "com", "net") array_shift($parts); // Return the first element, which is the subdomain return $parts[0]; }
Example Usage
To retrieve the subdomain from a URL, such as "en.example.com," you would use:
$subdomain = getSubdomain('en.example.com'); // "en"
Alternatively, using PHP 5.4 or later, you can simplify the process:
$subdomain = explode('.', 'en.example.com')[0]; // "en"
The above is the detailed content of How Can I Extract a Subdomain from a URL in PHP?. For more information, please follow other related articles on the PHP Chinese website!