天天看点

相对路径转换为绝对路径

<?php

function rel2abs($rel, $base)

{

/* return if already absolute URL */

if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;

/* queries and anchors */

if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;

/* parse base URL and convert to local variables:

$scheme, $host, $path */

extract(parse_url($base));

/* remove non-directory element from path */

$path = preg_replace('#/[^/]*$#', '', $path);

/* destroy path if relative url points to root */

if ($rel[0] == '/') $path = '';

/* dirty absolute URL */

$abs = "$host$path/$rel";

/* replace '//' or '/./' or '/foo/../' with '/' */

$re = array('#(//.?/)#', '#/(?!/./.)[^/]+//././#');

for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}

/* absolute URL is ready! */

return $scheme.'://'.$abs;

}

?>

Table 1. Conversion Results

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

../../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

../../x/y/lena.jpg

http://www.example.com/x/y/lena.jpg

http://google.com

http://google.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