PHP function that gets the hostname (subdomain+domain) from an URL

This functions extracts the subdomain + domain from an URL. For example for the $url: “http://mail.google.com/example” it would return “mail.google.com”. It does so by first removing the http protocol, and then considering the text up until the first “/” it encounters to be part of the hostname.

Note that this function only works for URLs with the http and https protocol. For other protocols, you can either use another str_replace function, or adapt it to a more general solution (remove all text before and including “//”).

function get_hostname_from_url($url)
{
	$url = str_replace("https://","", $url);
	$url = str_replace("http://","", $url);
	$domain = '';
	$i = 0;
	while ($i < strlen($url))
	{
		if ($url[$i] == '/') break;
		$domain .= $url[$i];
		$i++;
	}
	return $domain;
}

Leave a Reply

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close