Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Get Root Domain from a URL with PHP

Finding the root domain name (and TLD, or top level domain) from a URL is challenging. Literature on the web generally leans towards a library that'll find the root domain by way of comparing the URL against all approved top level domains ... but this method introduces a degree of complexity that we wanted to avoid. The following function is one that we use to find a domain name root (or TLD). It isn't perfect, but it's close.

1
<?php 
2
/*
3
 Get Root Domain (or TLD) from a URL with PHP
4
 http://www.beliefmedia.com/root-domain-url-php
5
*/
6
 
7
function beliefmedia_get_domain($url, $tld = false) {
8
  $pieces = parse_url($url);
9
  $domain = isset($pieces['host']) ? $pieces['host'] : '';
10
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $m)) {
11
    return ($tld === true) ? substr($m['domain'], ($pos = strpos($m['domain'], '.')) !== false ? $pos + 1 : 0) : $m['domain'];
12
  }
13
 return false;
14
}
15
 
16
/* Usage: returns 'beliefmedia.com' */
17
echo beliefmedia_get_domain(&quot;http://something.something.beliefmedia.com/directory/filename.php&quot;);
18
 
19
/* Usage: returns 'com.au' */
20
// echo beliefmedia_get_domain(&quot;http://something.something.beliefmedia.com.au/directory/filename.php&quot;, $tld = true);

You may optionally return the top level domain (eg, .com.au or .net) with the argument $tld = true.

Download


Title: Get Root Domain from a URL with PHP
Description: Get Root Domain from a URL with PHP.
  Download • Version 0.3, 580.0B, zip, Category: PHP Code & Snippets

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Connecticut)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433