用PHP計算相對路徑

來源:互聯網
上載者:User

假如現在有兩個路徑:

$a = "/a/b/c/d/test.php";

$b = "/a/b/e/f/other.php";

請用PHP設計一個函數,計算出$b相對於$a的路徑。

大致演算法就是:  根據‘/’把路徑拆分放進數組,然後從第一個開始比較,相同的忽略掉,直到遇到不同的為止。

<?php
$a = "/a/b/c/d/test.php";
$b = "/a/b/e/f/other.php";

//拆分路徑放進數組:
$_a = explode('/', $a);
$_b = explode('/', $b);

//開始比對數組,存下不同的部分:
$remain_a = array_diff($_a, $_b);
$remain_b = array_diff($_b, $_a);

 

 

//$remain_a = array("c", "d", "test.php");
//$remain_b = array("e", "f", "other.php") ;
//算出$a路徑的剩餘深度
$count = count($remain_a);

//算出$b剩餘路徑,再合并成路徑形式: $b = "e/f/other.php"
$relative_path_b = join('/', $remain_b);

//計算相對路徑首碼
for($i = 0; $i < $count-1; $i++)
{
     $new .= '../';
}
$_path = $new . $relative_path_b;

 //輸出 ../../e/f/other.php
echo $_path; 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.