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
8
9
$domain = isset($pieces['host']) ? $pieces['host'] : '';
10
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("http://something.something.beliefmedia.com/directory/filename.php");
18
19
/* Usage: returns 'com.au' */
20
// echo beliefmedia_get_domain("http://something.something.beliefmedia.com.au/directory/filename.php", $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