Shyam's answer is the best. You just need to make sure that all URLs start with HTTP and add strtok to the end (see below). Here's another version using an array:
function get_domain($url) { $urlobj = parse_url($url); $domain = $urlobj['host']; if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[az\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } return false; } $urls = array( 'http://www.subdomain.domain1.com/', 'http://www.subdomain.domain2.net', 'http://subdomain.subdomain2.domain3.org/', 'http://domain4.com' ); // Using foreach + strtok to remove .[domain extensions] echo "<ul>"; foreach($urls as $url) { echo "<li>" . strtok(get_domain($url),'.') . "</li>"; } echo "</ul>";
This will output:
- domain1
- domain2
- DOMAIN3
- domain4
PS you can add strtok to a function as shown below:
function get_domain($url) { $urlobj = parse_url($url); $domain = $urlobj['host']; if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[az\.]{2,6})$/i', $domain, $regs)) { return strtok($regs['domain'], '.'); } return false; }
then
$urls = array( 'http://www.subdomain.domain1.com/', 'http://www.subdomain.domain2.net', 'http://subdomain.subdomain2.domain3.org/', 'http://domain4.com' ); // Using foreach echo "<ul>"; foreach($urls as $url) { echo "<li>" . get_domain($url) . "</li>"; } echo "</ul>";
Minus ul / li:
$urls = array( 'http://www.subdomain.domain1.com/', 'http://www.subdomain.domain2.net', 'http://subdomain.subdomain2.domain3.org/', 'http://domain4.com' ); // Using foreach foreach($urls as $url) { echo get_domain($url)."<br>"; }
Conclusion: vacation rental domain1
domain2
DOMAIN3
domain4
source share