How to calculate relative paths of two files in php

不言
Release: 2023-04-02 11:12:02
Original
1588 people have browsed it

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(&#39;/&#39;, dirname($path1));
    $arr2 = explode(&#39;/&#39;, 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(&#39;/&#39;, $return_path);
}
//测试一下
$a = &#39;/a/b/c/d/e.php&#39;;
$b = &#39;/a/b/12/34/c.php&#39;;
echo relative_path($a, $b);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template