相对路径转换为绝对路径

时间:2022-11-27 13:44:05
function rel2abs($rel, $base)  
{  
    $rel = str_replace('\\', '/', $rel);                                //替换‘\’为'/' 
    $base = str_replace('\\', '/', $base); 
    if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;             //绝对地址 
    if ($rel[0]=='#') return $base.$rel;                                //# 
    if($rel[0]=='?') return preg_replace('#\?[^/]*$#', '', $base).$rel; //? 
    extract(parse_url($base));                                          //解析URL并将组成部分导入到当前的符号表 
    $path = preg_replace('#/[^/]*$#', '', $path);                       //去除非路径部分 
    if ($rel[0] == '/') $path = '';                                     //绝对路径 
    if(isset($port)) $host .= ":$port";                                     //带端口 
    $abs = "$host$path/$rel";                                           //路径 
    $re = array('#(/\.?/)#', '#/[\w-.]+/\.\./#');                       //将 '//' 或'/./'或 '/foo/../' 替换为 '/'  
    for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {} 
    return $scheme.'://'.$abs;                                          //最终地址 
}

 

Relative URL Absolute URL
lena.jpg http://www.example.com/a/b/lena.jpg
./lena.jpg http://www.example.com/a/b/lena.jpg
../lena.jpg http://www.example.com/a/lena.jpg
http://www.cnblogs.com/lena.jpg http://www.example.com/lena.jpg
/lena.jpg http://www.example.com/lena.jpg
../x/lena.jpg http://www.example.com/a/x/lena.jpg
http://www.cnblogs.com/x/y/lena.jpg http://www.example.com/x/y/lena.jpg
http://google.com http://google.com
http://www.cnblogs.com/x/y/lena.jpg http://www.example.com/x/y/lena.jpg
?w=90&h=60&f=lena.jpg http://www.example.com/a/b/c?w=90&h=60&f=lena.jpg
#lena http://www.example.com/a/b/c#lena