Created
June 18, 2011 12:46
-
-
Save woodywang/1033062 to your computer and use it in GitHub Desktop.
Convert a relative URL to absolute one, depends on the current base URL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function convertRelativeToAbsolute($relativeUrl, $baseUrl) | |
{ | |
preg_match('/^([\w\d]+?):\/\/([^\/]+)(\/[^\?#\.]+)?/', $baseUrl, $match); | |
$scheme = $match[1]; | |
$host = $match[2]; | |
$basePath = '/'; | |
if(!empty($match[3])) | |
{ | |
$basePath = $match[3]; | |
} | |
$baseDir = substr($basePath, 0, strrpos($basePath, '/')); | |
if(strpos($relativeUrl, '?') !== false) | |
{ | |
list($relativeUrl, $queryString) = explode('?', $relativeUrl); | |
} | |
$currentDirArr = explode('/', $baseDir); | |
$relativeUrlArr = explode('/', $relativeUrl); | |
foreach($relativeUrlArr as $dir) | |
{ | |
if($dir == '..') | |
{ | |
array_pop($currentDirArr); | |
} | |
else if($dir != '.') | |
{ | |
$currentDirArr[] = $dir; | |
} | |
} | |
$absUrl = "$scheme://$host" . '/' . ltrim(implode('/', $currentDirArr), '/'); | |
if(!empty($queryString)) | |
{ | |
$absUrl .= "?$queryString"; | |
} | |
return $absUrl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment