How to remove http://, www and slash from URL in PHP?

How to remove http://, www and slash from URL in PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

Stripping Protocol and Prefixes from URLs in PHP

Extracting a clean domain name from a raw URL string is a common requirement when building APIs, logging systems, or analytics pipelines. The goal is to normalize inputs like http://www.google.com/ into a canonical form such as google.com, regardless of whether the protocol, subdomain prefix, or trailing slash exists. While the native parse_url() function provides access to individual components, it does not automatically reconstruct the string in the specific format requested by your application logic. You often need to manually orchestrate the extraction and reassembly steps to handle edge cases robustly.

Using parse_url for Component Extraction

The most reliable approach involves using PHP's built-in parse_url() function to break the input string into its constituent parts. This function returns an associative array containing keys like scheme, host, and path. By inspecting these keys, you can conditionally remove the protocol and reconstruct only the host portion.

Consider a helper function that accepts a URL string:

function getCleanDomain(string $url): ?string {
    // Handle null or empty inputs gracefully
    if (empty($url)) {
        return null;
    }

    $parsed = @parse_url($url);

    // If parse_url fails, return null or handle as invalid
    if ($parsed === false) {
        return null;
    }

    // Extract just the host part. 
    // Note: parse_url might include a path like 'www.google.com/path' in the 'host' key 
    // if the URL is malformed, but for standard inputs it isolates the host well.
    $host = $parsed['host'] ?? null;

    if (!$host) {
        return null;
    }

    return $host;
}

However, relying solely on parse_url() can be tricky depending on the input format. If you pass a string like www.google.com/ (without a protocol), parse_url() might fail or return an incomplete structure because it expects a scheme to identify the host reliably in some versions or configurations. In such cases, normalizing the input first is a safer strategy.

Normalizing Input Before Parsing

To ensure consistency across all variations—whether the input has http://, lacks www, or includes a trailing slash—the most robust method is to use PHP's filter_var() function with the FILTER_VALIDATE_URL filter, combined with manual stripping if necessary. Alternatively, you can leverage explode() to manually remove known prefixes.

Here is a more comprehensive implementation that handles the specific requirements of removing http://, www, and /:

function normalizeDomain(string $input): ?string {
    // Remove trailing slashes first
    $url = rtrim($input, '/');

    // Check if there is a protocol. If not, we treat it as a plain domain.
    if (!str_starts_with($url, 'http://') && !str_starts_with($url, 'https://')) {
        // Remove leading www. if present without protocol
        if (str_starts_with($url, 'www.')) {
            $url = substr($url, 4);
        }
    } else {
        // If a protocol exists, extract the host using parse_url or regex
        $parsed = @parse_url($url);
        if ($parsed && isset($parsed['host'])) {
            return $parsed['host'];
        }
        
        // Fallback for malformed URLs with protocol but no valid host parsing
        // Split by '://' to isolate the part after the scheme
        $parts = explode('://', $url, 2);
        if (count($parts) === 2) {
            $hostPart = explode('/', $parts[1], 2)[0];
            return preg_replace('/^www\./i', '', $hostPart);
        }
    }

    // Final cleanup: remove any remaining 'www.' prefix regardless of protocol presence
    if (str_starts_with($url, 'www.')) {
        return substr($url, 4);
    }

    return $url ?: null;
}

This logic covers the examples provided in your source material. For instance, http://www.google.com/ becomes google.com by stripping the scheme and the prefix. Similarly, google.com/ remains google.com after trimming the trailing slash. The use of str_starts_with() is preferred over regex for these simple string operations because it offers better performance and readability in modern PHP versions (7.3+).

Trade-offs and Security Considerations

When implementing URL sanitization, always consider the source of the data. If you are processing user-generated content, relying on string manipulation alone can be risky if the input is malformed. A strict regex approach might inadvertently accept invalid characters that look like domains but aren't. For example, a pattern like ^[a-z0-9.-]+\.com$/ ensures only alphanumeric characters and dots are present before returning the result.

Additionally, be aware of IPv4 or IPv6 addresses embedded in URLs. The requirement to remove www and slashes usually implies you want a human-readable domain name. If an input is http://192.168.1.1/, your current logic would correctly return 192.168.1.1. If your application strictly requires a domain name (FQDN), you may need to add validation to reject or transform IP addresses depending on business rules.

For projects built on Laravel, you might find utility helpers in packages like spatie/laravel-backup or custom service classes that handle this normalization within larger routing or logging pipelines. However, for lightweight scripts or standalone functions, the manual parsing approach described above remains the most transparent and controllable solution.

Our network