Chinaunix首页 | 论坛 | 博客
  • 博客访问: 9033
  • 博文数量: 6
  • 博客积分: 180
  • 博客等级: 入伍新兵
  • 技术积分: 55
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-14 19:50
文章分类

全部博文(6)

文章存档

2011年(6)

我的朋友
最近访客

分类: 系统运维

2011-09-08 19:23:26

题目:写一个函数,算出两个文件的相对路径如 $a = '/a/b/c/d/e.php'; $b = '/a/b/12/34/c.php'; 计算出 $b 相对于 $a 的相对路径应该是 ../../c/d

答:
 
  1. <?php



  2. function getRelative($a , $b)

  3. {

  4. $arr_a = explode("/" , $a) ;

  5. $brr_b = explode("/" , $b) ;

  6. $i = 1 ;

  7. while (true) {

  8.      if($arr_a[$i] == $brr_b[$i]) {

  9.         $i ++ ;

  10.      } else {

  11.          break ;

  12.     }

  13. }

  14. $c = count($brr_b) ;

  15. $d = count($arr_a) ;

  16. $e = ($c>$d)?$c:$d ;

  17. $str1 = '' ;

  18. $str2 = '' ;

  19. for ($j = $i ;$j<$e ;$j++) {

  20.    if(isset($arr_a[$j])) {

  21.     if($j<($d-1)){

  22.      $str1 .= $arr_a[$j] . "/" ;

  23.     } else {

  24.      $str1 .= $arr_a[$j] ;

  25.     }
  26.    

  27.    }


  28.    if(isset($brr_b[$j])) {

  29.     $str2 .= "../" ;

  30.    }

  31. }

  32. return $str2 . $str1 ;

  33. }



  34. $a = "/c/b/c/d/k/h/t/e.php" ;

  35. $b = "/a/b/e/f/h.php" ;

  36. $relative = getRelative($a,$b) ;

  37. var_dump($relative);

  38. ?>
运行结果:string(34) "../../../../../c/b/c/d/k/h/t/e.php"

end up
阅读(352) | 评论(0) | 转发(0) |
0

上一篇:高效率PHP

下一篇:如何避免乱码

给主人留下些什么吧!~~