For example:
The path to file A is/home/web/lib/img/cache.php
The path to file B is/home/web/api/img/show.php
So, the path to file a relative to File B is ... /.. /lib/img/cache.php, that is, file B accesses the relative path of file a.
function Getrelativepath
<?php
/** calculates the path1 relative to path2 path, that is, the relative path of path2 reference paht1
* @param string $path 1
* @param string $ path2
* @return String
/function Getrelativepath ($path 1, $path 2) {
$arr 1 = explode ('/', $path 1);
$arr 2 = explode ('/', $path 2);
Gets part of the same path
$intersection = Array_intersect_assoc ($arr 1, $arr 2);
$depth = 0;
For ($i =0, $len =count ($intersection); $i < $len; $i + +) {
if (!isset ($intersection [$i])) {
$depth = $i;
break;
}
}
To path2 the/into. /,path1 gets the back part and then
$tmp = Array_merge (Array_fill (0, Count ($arr 2)-$depth-1, ' ... '), Array_slice ($arr 1, $depth));
$relativePath = implode ('/', $tmp);
return $relativePath;
>
Demo
<?php
$path 1 = '/home/web/lib/img/cache.php ';
$path 2 = '/home/web/api/img/show.php ';
Echo Getrelativepath ($path 1, $path 2); // .. /.. /lib/img/cache.php
?>
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/PHP/