解决方案 »

  1.   

    a = 'c/e.php';
    $b = '/12/34/c.php';
    echo getRelativePath($a, $b);  // ../../e.php
      

  2.   

    这样可能好些$a = '/c/e.php';
    $b = '/12/34/c.php';
    //  计算出 $b 相对于 $a 的相对路径应该是 ../../c/e.php
    function getRelativePath($a, $b) {
      $c['\\'] = '/'; 
      $a = explode('/', trim(strtr($a, $c), '/'));
      $b = explode('/', trim(strtr($b, $c), '/'));
      $t = array_intersect_assoc($a, $b);
      $r = array_merge(array_fill(0, count($b) - count($t) - 1, '..'), array_slice($a, count($t)));
      return join('/', $r);
    }
    echo getRelativePath($a, $b);
      

  3.   


    $a = '/home/web/lib/img/cache.php';
    $b = '/home/web/api/img/show.php';这样就不行了。
      

  4.   

    改了一下/** 计算path1 相对于 path2 的路径,即在path2引用paht1的相对路径 
    * @param  String $path1 
    * @param  String $path2 
    * @return String 
    */  
    function getRelativePath($path1, $path2){  
        $arr1 = explode('/', $path1);  
        $arr2 = explode('/', $path2);  
      
        // 获取相同路径的部分  
        $intersection = array_intersect_assoc($arr1, $arr2);  
      
        $depth = 0;  
      
        for($i=0,$len=count($intersection); $i<$len; $i++){  
            if(!isset($intersection[$i])){  
                $depth = $i;  
                break;  
            }  
        }  
      
        // 将path2的/ 转为 ../,path1获取后面的部分,然后合拼  
        $tmp = array_merge(array_fill(0, count($arr2)-$depth-1, '..'), array_slice($arr1, $depth));  
      
        $relativePath = implode('/', $tmp);  
      
        return $relativePath;  

      

  5.   

    function getRelativePath($a, $b) {
      $c['\\'] = '/'; 
      $a = explode('/', trim(strtr($a, $c), '/'));
      $b = explode('/', trim(strtr($b, $c), '/'));
      $t = 0;
      foreach($a as $k=>$v) {
        if($b[$k] == $v) $t++;
        else break;
      }
      $r = array_merge(array_fill(0, count($b) - $t, '..'), array_slice($a, $t));
      return join('/', $r);
    }$a = '/home/web/lib/img/cache.php';
    $b = '/home/web/api/img/show.php';echo getRelativePath($a, $b);