php源码之计算两个文件的相对路径
程序员文章站
2022-03-30 07:53:23
...
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)); ?>