This article mainly introduces relevant information on examples of implementing relative paths in the PHP algorithm. I hope this article can help everyone realize such a function. Friends in need can refer to it
php Algorithm Example of Implementing Relative Path
Calculate the relative path (the same directory can be ignored and represented by ../ or ./)
Implementation code:
class Relatively{ private function __construct(){ } /** * 算出相对路径(相同的目录可以忽略用../ 或者 ./ 表示) * @param Strint $path1 * @param Strint $path2 * @return string */ public static function relaroot($path1,$path2){ $rearray=array(); $arr1=explode('/', dirname($path1)); $arr2=explode('/', dirname($path2)); for($i=0,$len=count($arr2)-1;$i<$len;$i++){ if($arr1[$i]!=$arr2[$i]){ break; } if($i==1){ $rearray=array(); } if($i!=1 && $i<$len){ $rearray=array_fill(0,$len-$i,'..'); } if($i==$len){ $rearray=array('./'); } } $reroot=array_merge($rearray,array_slice($arr2, $i)); return implode('/', $reroot); } } $path1="a/b/c/d/index.php"; $path2="/a/b/12/34/index1.php"; $a=Relatively::relaroot($path1, $path2); echo $a;
The above is the detailed content of A case of implementing relative paths using PHP algorithm. For more information, please follow other related articles on the PHP Chinese website!