ramo ramo - 3 years ago 151
PHP Question

Get domain name from full URL

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

Answer Source

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'] : '';
  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'

?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download