-2

Get Domain Name with suffix (Only Domain)

I need regex in PHP or JavaScript to resolve domains.

any suffix (com,org,net,us,ar,....) And any Protocol (http,https,ftp,...)

Example:

array(
  , 'http://domainname.com'
  , 'http://domainname.com/whatever/you/get/the/idea'
  , 'http://www.domainname.com/whatever/you/get/the/idea'
  , 'http://www.domainname.com'
  , 'https://s1.s2.domainname.com/321.com/www.654.vom/'
  , 'https://s1.domainname.com'
  , 'https://s1.domainname.com/domain1.com/'
  , 'https://domain1.com.domainname.com'
  , 's1.s2.domainname.com/321.com/www.654.vom/'
  , 's1.domainname.com'
  , 's1.domainname.com/domain1.com/'
  , 'domain1.com.domainname.com'
);

Result: for all Result is domainname.com

Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54
user3770797
  • 374
  • 5
  • 24
  • possible duplicate of [Regex to find domain name without www](http://stackoverflow.com/questions/17427603/regex-to-find-domain-name-without-www) – CyanAngel Jun 24 '14 at 11:24
  • possible duplicate of [Use php to trim URL to just domain name by removing protocol and path](http://stackoverflow.com/questions/2122292/use-php-to-trim-url-to-just-domain-name-by-removing-protocol-and-path) – Chris Forrence Jun 26 '14 at 16:47

2 Answers2

1

JS, using the modern URL API:

   u = 'https://s1.s2.domainname.com/321.com/www.654.vom/'
   host = new URL(u).host.split('.').slice(-2).join('.')

An old-style regex way

   host = u.match(/^\w+:\/\/.*?(\w+\.\w+)(\/|$)/)[1]
georg
  • 211,518
  • 52
  • 313
  • 390
0

A way without regex:

$urls = array('http://domainname.com',
              'http://domainname.com/whatever/you/get/the/idea',
              'http://www.domainname.com/whatever/you/get/the/idea',
              'http://www.domainname.com',
              'https://s1.s2.domainname.com/321.com/www.654.vom/',
              'https://s1.domainname.com',
              'https://s1.domainname.com/domain1.com/',
              'https://domain1.com.domainname.com');

$domains = array_map(function ($url) {
    $chunks = explode('.', parse_url($url,PHP_URL_HOST));
    $first_level_dn = array_pop($chunks);
    return array_pop($chunks) . '.' . $first_level_dn;
}, $urls);

print_r($domains);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125