php相对url到绝对url的转换,最终使用basehrefhtml标记


php relative urls to absolute urls conversion with eventually base href html tag

我有一个加载了DOM的页面,然后我想最终根据<base href>标签将锚点的所有相对URL转换为绝对URL

我正在寻找一些经过测试的东西,而不是一些在某些情况下失败的随机脚本

我对解析href="用法的每一种形式都感兴趣:

href="relative.php"
href="/absolute1.php"
href="./relative.php"
href="../relative.php"
href="//absolutedomain.org"
href="." relative
href=".." relative
href="../" relative
href="./" relative

和更复杂的混合

提前感谢

<?php
//Converting relative urls into absolute urls | PHP Tutors
$base_url = 'http://www.xyz.com/ ';
$anchors[0] = '<a href="test1.php" >Testing Link1 </a >';
$anchors[1] = '<a href="test2.php" >Testing Link2 </a >';
foreach($anchors as $val) {
    if(strpos($val,$base_url) === false) {
        echo str_replace('href="','href="'.$base_url,$val)."<br/ >";
    } else {
        echo $val."<br/ >";
    }
}
?>

参考

此函数将在不使用正则表达式的情况下,将相对url解析为$pgurl中给定的当前页面url。它成功地解决了:

/home.php?example型,

相同目录nextpage.php类型,

../...../.../parentdir型,

完整的http://example.net URL,

和简写//example.net urls

//Current base URL (you can dynamically retrieve from $_SERVER)
$pgurl = 'http://example.com/scripts/php/absurl.php';
function absurl($url) {
 global $pgurl;
 if(strpos($url,'://')) return $url; //already absolute
 if(substr($url,0,2)=='//') return 'http:'.$url; //shorthand scheme
 if($url[0]=='/') return parse_url($pgurl,PHP_URL_SCHEME).'://'.parse_url($pgurl,PHP_URL_HOST).$url; //just add domain
 if(strpos($pgurl,'/',9)===false) $pgurl .= '/'; //add slash to domain if needed
 return substr($pgurl,0,strrpos($pgurl,'/')+1).$url; //for relative links, gets current directory and appends new filename
}
function nodots($path) { //Resolve dot dot slashes, no regex!
 $arr1 = explode('/',$path);
 $arr2 = array();
 foreach($arr1 as $seg) {
  switch($seg) {
   case '.':
    break;
   case '..':
    array_pop($arr2);
    break;
   case '...':
    array_pop($arr2); array_pop($arr2);
    break;
   case '....':
    array_pop($arr2); array_pop($arr2); array_pop($arr2);
    break;
   case '.....':
    array_pop($arr2); array_pop($arr2); array_pop($arr2); array_pop($arr2);
    break;
   default:
    $arr2[] = $seg;
  }
 }
 return implode('/',$arr2);
}

用法示例:

echo nodots(absurl('../index.html'));

在URL转换为绝对值后,必须调用nodots()

dots函数有点多余,但可读性强,速度快,不使用正则表达式,可以解析99%的典型URL(如果你想100%确定,只需扩展开关块以支持6+个点,尽管我从未见过URL中有这么多点)。

希望这有帮助,