PHP function to get the subdomain of a URL

PHP function to get the subdomain of a URL

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Subdomains in PHP: A Practical Approach

When parsing a URL like en.example.com, you are essentially looking for the first label in the host component before the second-level domain. There is no single built-in function named getSubdomain() in the standard PHP core, but extracting this value is a straightforward exercise in string manipulation once the host is isolated.

The most robust method involves leveraging parse_url() combined with a regular expression or a simple array split. The parse_url() function returns an associative array where the host key holds the full domain name. From there, you can strip the root domain to reveal the subdomain.

Consider this common scenario: you have a URL string and need to isolate the language code (like "en") from the rest of the address.

$url = 'https://en.example.com/path/to/page';

// Step 1: Parse the URL to get the host
$parsedUrl = parse_url($url);
$host = $parsedUrl['host'] ?? '';

if ($host) {
    // Step 2: Split the host by dots
    $parts = explode('.', $host);

    // Step 3: Check if there is at least one part before the last two (assuming standard domain structure)
    // This logic assumes a TLD and SLD (e.g., example.com).
    // If count($parts) > 2, the first element(s) are subdomains.
    $subdomainParts = array_slice($parts, 0, -2);
    
    // Join them back if there were multiple levels, or take the first one for single-level
    $subdomain = implode('.', $subdomainParts);

    echo $subdomain; // Output: en
}

This approach is reliable because it relies on the structure of DNS names rather than brittle string positions. However, you must account for edge cases. What happens if the host is just example.com? In that case, array_slice with an offset of -2 on an array of length 2 results in an empty array, and implode returns an empty string. This is often the desired behavior (no subdomain), but you should verify your logic matches your specific requirements for handling root domains versus subdomains.

Handling Multiple Subdomain Levels

Sometimes a URL might look like fr.de.example.com. Does "fr" or "fr.de" count as the subdomain? The code above extracts everything before the last two labels, resulting in fr.de. This is generally correct for identifying the immediate prefix of the public suffix. If your application only cares about the first label (e.g., just fr), you can simply grab $parts[0] if it exists.

Regex as an Alternative

For complex validation or when you need to enforce specific patterns, regular expressions offer a concise alternative. The preg_match() function can capture the leading segment directly.

$url = 'https://en.example.com';
$parsedUrl = parse_url($url);
$host = $parsedUrl['host'] ?? '';

if ($host) {
    // Capture one or more segments before the final two dots
    preg_match('/^(.+)\.(?!.*\.)([^.]+\.[^.]+)$/', $host, $matches);
    
    // This regex is tricky to get right for all edge cases (like IDN domains).
    // The string split method above is usually preferred for simplicity.
}

Actually, a simpler regex pattern often used in production is:
/^([^.]*)(\.[^.]+)$/. Wait, that captures the last part. To capture the subdomain prefix specifically before the root domain (assuming a standard 2-part root), you can use:

preg_match('/^(.+)\.(.+)$/', $host, $matches);
// This splits into two groups. Group 1 is everything before the last dot.
// If the host is "en.example.com", Group 1 is "en.example".
// If the host is "example.com", Group 1 is empty (if logic handles split carefully).

Actually, the regex approach can get messy with TLDs that contain hyphens or unusual lengths. The array splitting method remains the gold standard for stability unless you have strict validation requirements.

Performance Considerations

If you are processing millions of URLs in a loop, avoid using explode() inside a tight cycle if a more efficient alternative exists, though for simple string parsing, the overhead is negligible. The real bottleneck is usually network I/O or database lookups, not the substring extraction itself.

However, be wary of dynamic DNS setups where the root domain changes. If your logic assumes example.com is always the root, you might incorrectly treat app.example.com as a subdomain while sub.app.example.com becomes the target. Always identify the Public Suffix List (PSL) if you need to handle edge cases like .co.uk or .com.au correctly, as these have multiple levels in their TLD.

Summary of Best Practices

  1. Use parse_url(): It handles protocol prefixes and port numbers automatically.
  2. Split by dot: It is readable and easy to debug.
  3. Handle the root domain: Explicitly check the count of parts before slicing to avoid empty strings or incorrect splits on short domains.
  4. Consider PSL: For enterprise-grade applications dealing with internationalized domains, consider libraries that respect the Public Suffix List rather than blindly assuming the last two labels are the root.

For developers using the Laravel framework, you can extend Illuminate\Support\Str to add a helper method if this logic is used frequently across your codebase. Alternatively, creating a reusable class utility within your project keeps the namespace clean without modifying core packages.

Our network