php

PHP – Get Domain Name from URL

In this tutorial, we are going to see how to get the domain name from a URL. Using the script below, you will be able to extract only the domain name from any type of URL.

All the PHP code is bundled in getDomainFrom() function. The $url parameter must be transmitted to the getDomainFrom() function, from which you want to get the domain name. getDomainFrom() function returns the domain name if it is found and FALSE if it is not found.
 

Method 1: Get Domain Name from URL
<?php
	function getDomainFrom($url)
	{
	  $pieces = parse_url($url);
	  $domain = isset($pieces['host']) ? $pieces['host'] : $pieces['path'];
	  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
		return $regs['domain'];
	  }
	  return false;
	}

	print getDomainFrom("https://stackhowto.com/contact"); 
?>

Output:

stackhowto.com
[st_adsense]  

Method 2: Get Domain Name from URL

You can also use the parse_url() function but often does not handle URLs very well, but is fine in some cases.

<?php
	$url = 'https://stackhowto.com/contact';
	$parse = parse_url($url);
	echo $parse['host']; 
?>

Output:

stackhowto.com
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More [st_adsense]

One thought on “PHP – Get Domain Name from URL

  • You can also use a flag, like so: parse_url($value, PHP_URL_HOST)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *