Get domain name from full URL

Check the code below, it should do the job fine.

<?php

function get_domain($url)
{
  $pieces = parse_url($url);
  $domain = isset($pieces['host']) ? $pieces['host'] : $pieces['path'];
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
    return $regs['domain'];
  }
  return false;
}

print get_domain("http://mail.somedomain.co.uk"); // outputs 'somedomain.co.uk'

?>

You need package that using Public Suffix List. Yes, you can use string functions arround parse_url() or regex, but they will produce incorrect result in complex URLs.

I recomend TLDExtract for domain parsing, here is sample code:

$url = 'http://i.imgur.com/a/b/c?query=value&query2=value';

parse_url($url, PHP_URL_HOST); // will return 'i.imgur.com'

$extract = new LayerShifter\TLDExtract\Extract();
$result = $extract->parse($url);
$result->getFullHost(); // will return 'i.imgur.com'
$result->getSubdomain(); // will return 'i'
$result->getRegistrableDomain(); // will return 'imgur.com'
$result->getSuffix(); // will return 'com'

I have found a very useful library using publicsuffix.org, PHP Domain Parser is a Public Suffix List based domain parser implemented in PHP.

https://github.com/jeremykendall/php-domain-parser

 <?php 
 // this will do the job

 require_once '../vendor/autoload.php';

 $pslManager = new Pdp\PublicSuffixListManager();
 $parser = new Pdp\Parser($pslManager->getList());
 var_dump($parser->getRegistrableDomain('www.scottwills.co.uk'));
 ?>

string(16) "scottwills.co.uk"