PHP: Get Main Base URL
Posted on September 8, 2008, Filled under PHP,
Bookmark it
Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.
This is a snippet which extracts the Main Base Address from a complete URL:
<?php
function GetMainBaseFromURL($url)
{
$chars = preg_split('//', $url, -1, PREG_SPLIT_NO_EMPTY);
$slash = 3; // 3rd slash
$i = 0;
foreach($chars as $key => $char)
{
if($char == '/')
{
$j = $i++;
}
if($i == 3)
{
$pos = $key; break;
}
}
$main_base = substr($url, 0, $pos);
return $main_base.'/';
}
$url = 'http://mysubdomain.mydomain.com/category/hardware/subcategory/mainboards.html';
$main_base = GetMainBaseFromURL($url);
// Output: http://mysubdomain.mydomain.com/
echo $main_base;
?>
