元となるURLとそれに対する相対パスを指定すると絶対URLを作成する関数です。
元URL:http://www.test.com/gallery/index.html 相対パス:../contact.html URL:http://www.test.com/contact.html
使い方
$url = make_uri('元url','相対パス');
です。
//================ make_uri:version 1.4
function make_uri($base='', $rel_path=''){
$base = preg_replace('/\/[^\/]+$/','/',$base);
$parse = parse_url($base);
if (preg_match('/^https\:\/\//',$rel_path) ){
return $rel_path;
}
elseif ( preg_match('/^\/.+/', $rel_path) ){
$out = $parse['scheme'].'://'.$parse['host'].$rel_path;
return $out;
}
$tmp = array();
$a = array();
$b = array();
$tmp = preg_split("/\//",$parse['path']);
foreach ($tmp as $v){
if ($v){ array_push($a,$v); }
}
$b = preg_split("/\//",$rel_path);
foreach ($b as $v){
if ( strcmp($v,'')==0 ){ continue; }
elseif ($v=='.'){}
elseif($v=='..'){ array_pop($a); }
else{ array_push($a,$v); }
}
$path = join('/',$a);
$out = $parse['scheme'].'://'.$parse['host'].'/'.$path;
return $out;
}
//============= make_apath:version 1.1
function make_apath($base='', $rel_path=''){
$base = preg_replace('/\/[^\/]+$/','/',$base);
$parse = parse_url($base);
if (preg_match('/^https\:\/\//',$rel_path) ){
return $rel_path;
}
elseif ( preg_match('/^\/.+/', $rel_path) ){
$out = $parse['scheme'].'://'.$parse['host'].$rel_path;
return $out;
}
$tmp = array();
$a = array();
$b = array();
$tmp = preg_split("/\//",$parse['path']);
foreach ($tmp as $v){
if ($v){ array_push($a,$v); }
}
$b = preg_split("/\//",$rel_path);
foreach ($b as $v){
if ( strcmp($v,'')==0 ){ continue; }
elseif ($v=='.'){}
elseif($v=='..'){ array_pop($a); }
else{ array_push($a,$v); }
}
$path = join('/',$a);
return '/'.$path;
}