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

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

Linda Hamilton
Release: 2024-11-25 22:34:11
Original
248 people have browsed it

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];
}
Copy after login

Example Usage

To retrieve the subdomain from a URL, such as "en.example.com," you would use:

$subdomain = getSubdomain('en.example.com'); // "en"
Copy after login

Alternatively, using PHP 5.4 or later, you can simplify the process:

$subdomain = explode('.', 'en.example.com')[0]; // "en"
Copy after login

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!

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