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

A case of implementing relative paths using PHP algorithm

黄舟
Release: 2023-03-16 17:06:01
Original
2492 people have browsed it

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;
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template