Home >Backend Development >PHP Tutorial >PHP method to calculate relative paths of two files_PHP tutorial
This article describes the example of how PHP calculates the relative paths of two files. Share it with everyone for your reference. The details are as follows:
1. Question:
Write a php function to calculate the relative paths of two files. For example, $a="/a/b/c/d/e.php"; $b="/a/b/12/34/c.php", what is the relative path of B relative to A?
2. Solution:
<?php /** * 求$b相对于$a的相对路径 * @param string $a * @param string $b * @return string */ function getRelativePath ($a, $b) { $patha = explode('/', $a); $pathb = explode('/', $b); $counta = count($patha) - 1; $countb = count($pathb) - 1; $path = "../"; if ($countb > $counta) { while ($countb > $counta) { $path .= "../"; $countb --; } } // 寻找第一个公共结点 for ($i = $countb - 1; $i >= 0;) { if ($patha[$i] != $pathb[$i]) { $path .= "../"; $i --; } else { //判断是否为真正的第一个公共结点,防止出现子目录重名情况 for ($j = $i - 1, $flag = 1; $j >= 0; $j --) { if ($patha[$j] == $pathb[$j]) { continue; } else { $flag = 0; break; } } if ($flag) break; else $i ++; } } for ($i += 1; $i <p>I hope this article will be helpful to everyone’s PHP programming design. </p> <p align="left"></p><div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/969338.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/969338.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">How PHP calculates the relative paths of two files. This example describes how PHP calculates the relative paths of two files. Share it with everyone for your reference. The details are as follows: 1. Question: Write a...</span> </div> <div class="art_confoot"></div>