【问题标题】:php relative urls to absolute urls conversion with eventually base href html tag [duplicate]php相对url到绝对url的转换,最终使用base href html标签[重复]
【发布时间】:2012-07-25 15:49:31
【问题描述】:

我有一个加载了 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 html 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/ >";
    }
}
?>

Reference

【讨论】:

    【解决方案2】:

    此函数将在$pgurl 没有正则表达式中将相对 URL 解析为 给定当前页面 URL。成功解决:

    /home.php?example 类型,

    same-dir nextpage.php 类型,

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

    完整的http://example.net 网址,

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

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

    dots 函数有点多余,但可读、快速、不使用正则表达式,并且可以解析 99% 的典型 url(如果你想 100% 确定,只需扩展 switch 块以支持 6+点,虽然我从未在 URL 中看到过这么多点)。

    希望这会有所帮助,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-24
      • 2014-12-12
      • 2011-07-08
      • 2011-05-25
      • 2021-07-28
      • 2011-08-04
      相关资源
      最近更新 更多