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: “” it would return “”. 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];
	return $domain;

Leave a Reply

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

12 + thirteen =

This site uses Akismet to reduce spam. Learn how your comment data is processed.