Building off of Shyam's answer and employing the concept suggested by Mark Baker to get the penultimate element of the namespace, I might suggest using a simpler regular expression that utilizes an anchored lookahead like the following:
function get_domain($url) {
$matches = [];
preg_match('/[\w-]+(?=(?:\.\w{2,6}){1,2}(?:\/|$))/', $url, $matches);
return $matches[0];
}
Matches
names in https://www.names.co.uk/
domain1 in http://www.subdomain.domain1.com/
domain2 in www.subdomain.domain2.net
domain3 in subdomain.subdomain2.domain3.org/
domain4 in http://domain4.com
seventymm in http://www.seventymm.co.in/browse/buy-home-furnishing-bed-sheets-pack-of-3/2456/1/v2034/0/0/1/2/1/0/go