A small study on the relative path method
Release: 2016-07-25 09:02:37
Original
1165 people have browsed it
As in the title, find the relative paths of two paths, and ask for a brick!
- /**
- * Find the relative path of two paths
- * @param string $patha path a
- * @param string $pathb path b
- * @author Joychao
- * @link http://www.joychao .cc
- * @return string relative path
- */
- function getRelativePath($patha,$pathb){
- $arr_a=explode('/',trim(dirname($patha),'/'));
- $arr_b =explode('/',trim(dirname($pathb),'/'));
- $n=min(count($arr_a),count($arr_b));//Use the shortest path to loop
- $flag =true;//Mark bit [whether the mark has no intersection at all]
- for($i=0;$i<$n;$i++){
- if($arr_a[$i]==$arr_b[$i]) {
- unset($arr_a[$i],$arr_b[$i]);//Remove the same part before
- }else{
- if($i==0)
- $flag=false;//There are no two paths Intersection
- break;//Stop the loop
- }
- }
- $str=$flag?str_repeat('../',count($arr_b)+1):'/';//If there is no intersection, it is the root directory" /"[Linux situation, Windows can change it by itself]
- return $str.join('/',$arr_a);//Splice and return
- }
- //TEST
- $a ='/a/b/c/d /e.php';
- $b ='/a/b/12/34/c.php';
- echo 'Path a:'.$a;
- echo '
Path b:'. $b;
- echo '
The relative path between path a and path b (use c.php to access the e.php path) is:';
- echo getRelativePath($a,$b);
- // -----OUTPUT-------------=
- Path a:/a/b/c/d/e.php
- Path b:/a/b/12/34/c .php
- The relative path between path a and path b (use c.php to access the e.php path) is: ../../../c/d
Copy the code
|
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31