Home >Backend Development >PHP Tutorial >A case of implementing relative paths using PHP algorithm

A case of implementing relative paths using PHP algorithm

黄舟
黄舟Original
2017-10-18 09:06:302502browse

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,&#39;..&#39;); 
      } 
      if($i==$len){ 
        $rearray=array(&#39;./&#39;); 
      } 
    } 
    $reroot=array_merge($rearray,array_slice($arr2, $i)); 
    return implode(&#39;/&#39;, $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!

Statement:
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