现在的位置: 首页 > 综合 > 正文

PHP计算两个路径的相对路径

2012年09月07日 ⁄ 综合 ⁄ 共 550字 ⁄ 字号 评论关闭
 1 <html>
 2     <body>
 3         <?php
 4             function relativePath($aPath, $bPath) {
 5                 $aArr = explode('/', $aPath);    //explode函数用于切分字符串,返回切分后的数组,此处用'/'切分字符串
 6                 $bArr = explode('/', $bPath);
 7                 $aDiffToB = array_diff_assoc($aArr, $bArr);    //array_diff_assoc()用于获取A数组与B数组之间元素的差集,Key和Value都不相同视为不同元素,此处返回在A数组中且与B数组不相同的元素
 8                 $count = count($aDiffToB);
 9                 
10                 $path = '';
11                 for($i = 0; $i < $count - 1; $i++){
12                     $path .= '../'; 
13                 }
14                 
15                 $path .= implode('/', $aDiffToB);    //implode()用于使用指定字符串连接数组元素,此处返回用'/'连接数组元素后的字符串
16                 
17                 return $path;
18             }
19             
20             echo relativePath('/a/b/c/d/a.php', '/a/b/1/2/b.php');
21         ?>
22     </body>
23 </html>

页面输出

. ./. ./c/d/a.php

抱歉!评论已关闭.