Function getRelativePath ($ a, $ B ){ $ ReturnPath = array (dirname ($ B )); $ ArrA = explode ('/', $ ); $ ArrB = explode ('/', $ returnPath [0]); For ($ n = 1, $ len = count ($ arrB); $ n <$ len; $ n ++ ){ If ($ arrA [$ n]! = $ ArrB [$ n]) { Break; } } If ($ len-$ n> 0 ){ $ ReturnPath = array_merge ($ returnPath, array_fill (1, $ len-$ n ,'..')); } $ ReturnPath = array_merge ($ returnPath, array_slice ($ arrA, $ n )); Return implode ('/', $ returnPath ); } Var_dump (getRelativePath ($ a, $ B )); // Method 2 $ A = "/a/B/c/d/index. php "; // Echo basename ($ a, '. php'); // part of the file name in the returned path // Echo dirname ($ ); $ B = "/a/B/12/34/index2.php "; Function getRelativePath ($ path1, $ path2 ){ $ P1 = dirname ($ path1 ); $ P2 = dirname ($ path2 ); $ Arr1 = explode ('/', $ p1 ); $ Arr2 = explode ('/', $ p2 ); $ Diff_arr = array_diff ($ arr2, $ arr1); // calculate the difference set. Pay attention to who is relative to whom. $ Inter_arr = array_intersect ($ arr1, $ arr2); // calculates the intersection $ Leng = count ($ inter_arr); // The length is calculated based on the intersection... For ($ I = 1; $ I <$ leng; $ I ++ ){ $ Inter_arr [$ I] = '..'; } $ Merge_arr = array_merge ($ inter_arr, $ diff_arr ); $ Fina_arr = implode ('/', $ merge_arr ); Return $ fina_arr; } Var_dump (getRelativePath ($ a, $ B )); // Return string '/.../../100' (length = 12) // If it is changed to $ diff_arr = array_diff ($ arr1, $ arr2); then string '/.../../c/d (length = 12) is returned) |