This code is rare used in #projects but I need it to generate email with domains for listings, in listings I have different types of complete url and domains I wrote this code to generate email address contact@sdtuts.com
function get_domain_from_url($url=''){ if(strpos($url,'http://')===false && strpos($url,'https://')===false){ $url = 'http://'.$url; } $url = str_replace('www.','',$url); $parsed_url = parse_url($url); if(isset($parsed_url['host'])){ return $parsed_url['host']; } else { return false; } }
Here is some of results example of function
echo get_domain_from_url('https://sdtuts.com/php-how-to-get-domain-from-url/'); //sdtuts.com echo get_domain_from_url('https://sdtuts.com/'); //sdtuts.com echo get_domain_from_url('https://www.sdtuts.com/'); //sdtuts.com echo get_domain_from_url('www.sdtuts.com/'); //sdtuts.com echo get_domain_from_url('http://www.sdtuts.com/'); //sdtuts.com echo get_domain_from_url('http://www.sdtuts.edu.pk/'); //sdtuts.edu.pk
-
This can also be achieved through a one liner code:
echo strtolower( parse_url( $string , PHP_URL_HOST ) );