PHP add subdomain in url

1.27K views
no comments
31 Mar 2019 2:50 am

I’ve wrote add_subdomain_in_url function and it will help you in easily add sub domain in url by passing in parameters and look output result.

function add_subdomain_in_url($url,$subdomain){
	$www_pos = strpos($url,'www.');
	$non_www_pos = strpos($url,'://');
	if($www_pos!==false){
		return substr($url,0, $www_pos+4).$subdomain.'.'.substr($url,$www_pos+4);
	} else if($non_www_pos!==false){
		return substr($url,0, $non_www_pos+3).$subdomain.'.'.substr($url,$non_www_pos+3);
	} else {
		return $subdomain.'.'.$url;
	}
}
echo add_subdomain_in_url('https://www.sdtuts.com','services').'/';
//https://www.services.sdtuts.com

echo add_subdomain_in_url('https://sdtuts.com','services').'/';
//https://services.sdtuts.com

echo add_subdomain_in_url('http://www.sdtuts.com/abc','services').'/';
//http://www.services.sdtuts.com/abc

echo add_subdomain_in_url('http://sdtuts.com','services').'/';
//http://www.services.sdtuts.com/abc

echo add_subdomain_in_url('www.sdtuts.com','services').'/';
//http://services.sdtuts.com

echo add_subdomain_in_url('sdtuts.com','services').'/';
//services.sdtuts.com

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>