phpurl

Get part of domain name


say someone enters a URL like this:

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

And I want to return: imgur.com

not i.imgur.com

This is code I have right now

$sourceUrl = parse_url($url);
$sourceUrl = $sourceUrl['host'];

But this returns i.imgur.com


Solution

  • 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'
    
    ?>