php - Get domain with its subdomain from url -


i'm using function domain , subdomain string. if string expected format, returns null

function getdomainfromurl($url) {     $host = parse_url($url, php_url_host);     return preg_replace('/^www\./', '', $host); }  $url = "http://abc.example.com/" -> abc.example.com | ok  $url = "http://www.example.com/" -> example.com | ok  $url = "abc.example.com" -> fails! 

the issue parse_url returning false. check make sure response before trying use otherwise $host empty.

<?php function getdomainfromurl($url) {     $host = (parse_url($url, php_url_host) != '') ? parse_url($url, php_url_host) : $url;     return preg_replace('/^www\./', '', $host); } echo getdomainfromurl("http://abc.example.com/") . "\n"; echo getdomainfromurl("http://www.example.com/") . "\n"; echo getdomainfromurl("abc.example.com"); 

output:

abc.example.com
example.com
abc.example.com


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -