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.