PHP - Strip URL to Domain

From Global Programming Syntax

Jump to: navigation, search

Have you ever needed to strip a url to just the domain name for some computer generaterated system whether it is for a search engine or a log file. So to solve this rarley used feature I have created a 2 functions as showen below. The first function gets something like http://www.subdomain.example.com/ while the second function on the page gets http://www.example.com and removes the subdomain.

Getting Domain + Subdomain Together

This domain function will remove anything after the domain and keep the subdomain in the returned string. So if you were to use it on the url www.subdomain.example.com/test.php then the returned result will be http://www.subdomain.example.com/

function fulldomain($domainb) {
$bits = explode('/', $domainb);
if ($bits[0]=='http:' || $bits[0]=='https:')
{
return $bits[0].'//'.$bits[2].'/';
} else {
return 'http://'.$bits[0].'/';
}
unset($bits);
}

And a second option using regex is as follows:

function fulldomain ($domainb) {
return preg_replace('/^((http(s)?:\/\/)?([^\/]+)(\/)?)(.*)/','$1',$domainb);
}

Getting Registered Domain & Not Subdomain

This domain function will remove anything after the domain and remove the subdomain in the returned string. So if you were to use it on the url www.subdomain.example.com/test.php then the returned result will be http://example.com/

function domain($domainb)
{
$bits = explode('/', $domainb);
if ($bits[0]=='http:' || $bits[0]=='https:')
{
$domainb= $bits[2];
} else {
$domainb= $bits[0];
}
unset($bits);
$bits = explode('.', $domainb);
$idz=count($bits);
$idz-=3;
if (strlen($bits[($idz+2)])==2) {
$url=$bits[$idz].'.'.$bits[($idz+1)].'.'.$bits[($idz+2)];
} else if (strlen($bits[($idz+2)])==0) {
$url=$bits[($idz)].'.'.$bits[($idz+1)];
} else {
$url=$bits[($idz+1)].'.'.$bits[($idz+2)];
}
return $url;
}

Using both of the above functions

To use the function first copy the above function to the top of your php document. Then to retrieve the domain name just use the below example but place your own url between the quotation marks and you may remove the 'echo' before the function if you do not wish to display the domain name. Below is an example of how to display the domain name of a url using the above function.

echo domain("http://www.subdomain.example.com.au/test/directory/index.html");
// -- or -- //
echo fulldomain("http://www.subdomain.example.com.au/test/directory/index.html");

Also if you are going to place the domain name in a sentence, Below is an example of what to do and what not to do:

echo "The domain is ".domain("http://www.asdf.example.com.au/test/directory/index.html")." and not http://www.test.com/";
 
 
//Below is what NOT to do due to an unreported syntax error.
echo 'The domain is domain("http://www.asdf.example.com.au/test/directory/index.html") and not http://www.test.com/';
Personal tools
languages
page stats
Toolbox