如$a=‘/a/b/c/d/e.php’;
$b='/a/b/12/34/c.php';
計算出$b相對於$a的相對路徑應該是../../c/d
個人答案如下:
首先我感覺b相對於a的路徑應該是../../12/34纔對,a相對於b纔是../../c/d
函數如下,求path1相對於path2的相對路徑
public static string getPath2(string path1, string path2)
{
string result = "";
string tempstr = "";
string[] arr1 = path1.Split('/');
string[] arr2 = path2.Split('/');
int parentNum = 0;
if (arr2.Length > arr1.Length)
{
parentNum= arr2.Length - arr1.Length;
}
for (int i = 0; i < arr1.Length - 1; i++)
{
if (i < arr2.Length && arr1[i] == arr2[i])
{
continue;
}
else
{
result += result == "" ? arr1[i] : "/" + arr1[i];
parentNum++;
}
}
if (parentNum > 0)
{
for (int i = 0; i < parentNum; i++)
{
tempstr += tempstr == "" ? ".." : "/..";
}
result = tempstr + (result == "" ? "" : "/" + result);
}
return result;
}
測試結果:
public static void Main()
{
Console.WriteLine(getPath2("/a/c/a.txt","/a/b/c/d/b.txt"));
Console.WriteLine(getPath2("/a/b/c/d/e/f/a.txt", "/a/b/c/d/b.txt"));
Console.WriteLine(getPath2("/a/b/12/34/a.txt", "/a/b/c/d/b.txt"));
Console.ReadKey();
}