An example of implementing relative path of php algorithm
- 2021-08-10 07:28:02
- OfStack
An example of implementing relative path of php algorithm
Calculate the relative path (the same directory can be ignored and represented by../or./)
Implementation code:
class Relatively{
private function __construct(){
}
/**
* Calculate the relative path (the same directory can be ignored with ../ Or ./ Represents)
* @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;
If you have any questions, please leave a message or go to this site community to exchange and discuss, thank you for reading, hope to help everyone, thank you for your support to this site!