RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Get Root Domain from a URL with PHP

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.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment