PHP相对URL转绝对URL的方法,最终使用基本href HTML标签。

3

我有一个已经加载了DOM的页面,现在我想根据<base href>标签,将所有锚点的相对链接转换为绝对链接。

我需要的是经过测试的可靠方法,而不是一些随机脚本,在某些情况下无法正常工作。

我需要解析每种使用href=""的方式:

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

和更复杂的混合体

提前感谢你


1
这是将相对路径转换为绝对URL的PHP代码的副本。 - qdinar
2个回答

1

这个函数将解析相对于$pgurl给定当前页面URL的相对URL,而无需使用正则表达式。它成功地解析了:

/home.php?example 类型的URL,

同一目录下的 nextpage.php 类型的URL,

../...../.../parentdir 类型的URL,

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

以及简写的 //example.net URL。

//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'));

nodots() 必须在 URL 转换为绝对路径之后调用。

点函数有点多余,但可读性高,速度快,不使用正则表达式,并且将解析 99% 的典型 URL(如果您想要 100% 确定,请扩展 switch 块以支持 6+ 个点,尽管我从未见过那么多点的 URL)。

希望这可以帮助到您,


1
<?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/ >";
    }
}
?>

参考资料


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接