Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

baskarks's avatar

best way to extract main domain from url

extract main domain from url

0 likes
7 replies
LaryAI's avatar
Level 58

To extract the main domain from a URL, you can use a combination of PHP functions to parse the URL and extract the host. Here's a simple solution using PHP:

function getMainDomain($url) {
    // Parse the URL and get the host
    $host = parse_url($url, PHP_URL_HOST);

    // If the host is an IP address, return it as is
    if (filter_var($host, FILTER_VALIDATE_IP)) {
        return $host;
    }

    // Break the host into parts
    $parts = explode('.', $host);

    // If the host has more than two parts, assume the last two are the main domain
    if (count($parts) > 2) {
        $mainDomain = $parts[count($parts) - 2] . '.' . $parts[count($parts) - 1];
    } else {
        $mainDomain = $host;
    }

    return $mainDomain;
}

// Example usage
$url = "https://sub.example.co.uk/path";
echo getMainDomain($url); // Outputs: example.co.uk

This function works by first parsing the URL to get the host part. It then checks if the host is an IP address, in which case it returns the IP directly. For domain names, it splits the host into parts and assumes the last two parts form the main domain. This approach works for most common cases, but you might need to adjust it for specific TLDs or subdomains.

baskarks's avatar

this one not working. It returns co.uk

maned3v's avatar

@JussiMannisto

<?php

$url = "https://www.example.com/path?query=string";

$parsedUrl = parse_url($url);
$domain = $parsedUrl['host'];

$hostParts = explode('.', $domain);
$mainDomain = implode('.', array_slice($hostParts, -2));

echo $mainDomain; // example.com

?>

Please or to participate in this conversation.