<?php //計算出兩個文件的相對路徑即path2相對於$path1的相對路徑 // http://www.manongjc.com/article/1342.html function get_relative_path($path1,$path2){ $arr1 = explode(DIRECTORY_SEPARATOR,dirname($path1)); $arr2 = explode(DIRECTORY_SEPARATOR,dirname($path2)); $length = count($arr2); for($i = 0; $i < $length; $i++){ if($arr1[$i] != $arr2[$i]){ //進行路徑匹配 break; } } if($i == 0){ //根目錄不同 return '不在同一個目錄中'; }else if($i != 0 && $i < $length){ //在同一個個目錄下 $separator = array_fill(0, ($length-$i), '..'); return(implode(DIRECTORY_SEPARATOR, array_merge($separator, array_slice($arr1, $i)))); }else if($i == $length){ //路徑完全相同 http://www.manongjc.com/article/1343.html return '.'; } } $path1 = 'F:\Apache\www\temp\php_demo\demo.md'; //參照路徑path1 $path2 = 'F:\Apache\www\temp\php_demo\demo.md'; $path3 = 'F:\Apache\www\temp\sd\ss.d\sdsfd'; $path4 = 'G:\FFOutput'; var_dump(get_relative_path($path1,$path2)); var_dump(get_relative_path($path1,$path3)); var_dump(get_relative_path($path1,$path4)); ?>