Home >Backend Development >PHP Tutorial >How to calculate relative paths of two files in php
This article mainly introduces the method of calculating the relative path of two files in PHP. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
<?php /** * 计算两个文件的相对路径 */ function relative_path($path1, $path2) { $arr1 = explode('/', dirname($path1)); $arr2 = explode('/', dirname($path2)); for ($i = 0, $len = count($arr2); $i < $len; $i++) { if ($arr1[$i] != $arr2[$i]) { break; } } //不在用一个根目录下面 if ($i == 1) { $return_path = array(); } //在同一个根目录下 if ($i != 1 && $i < $len) { $return_path = array_fill(0, $len - $i, ".."); } #在同一个目录下 if ($i == $len) { $return_path = array("./"); } $return_path = array_merge($return_path, array_slice($arr1, $i)); return implode('/', $return_path); } //测试一下 $a = '/a/b/c/d/e.php'; $b = '/a/b/12/34/c.php'; echo relative_path($a, $b);
The above is the content of this article. All content, I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
PHPExcel method of importing Excel data
php source code method of building a site to implement a login page
The above is the detailed content of How to calculate relative paths of two files in php. For more information, please follow other related articles on the PHP Chinese website!