php how to get domain from url

3.02K views
2 Comments
26 Apr 2016 12:16 am

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

NOTE:Your Email Address will be not shown and please do not add spamming comments because here is REL="NOFOLLOW" on your links and comments also moderated shown.
<code>Put html css or any language code under this tag</code>

2 Comments on php how to get domain from url
  • This can also be achieved through a one liner code:

    echo strtolower( parse_url( $string , PHP_URL_HOST ) );

    • Please keep posting unique things, do not copy function name or any text from other sites for your website.
      function get_domain_from_url( $string )
      {
      return strtolower( parse_url( $string , PHP_URL_HOST ) );
      }
      I call your one liner code and got the following result.
      echo get_domain_from_url(‘http://sdtuts.com/php-how-to-get-domain-from-url/’); //sdtuts.com //WORKING
      echo get_domain_from_url(‘http://sdtuts.com/’); //sdtuts.com //WORKING
      echo get_domain_from_url(‘https://www.sdtuts.com/’); //www.sdtuts.com //ITS RETURN WWW.
      echo get_domain_from_url(‘www.sdtuts.com/’); // RETURN NOTHING
      echo get_domain_from_url(‘http://www.sdtuts.com/’); //www.sdtuts.com //RETURN WITH WWW.
      echo get_domain_from_url(‘http://www.sdtuts.edu.pk/’); //www.sdtuts.edu.pk //RETURN WITH WWW.
      echo get_domain_from_url(‘http://sdtuts.edu.pk/’); //sdtuts.edu.pk //WORKING.