萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 計算兩檔案相對路徑函式實作

經典面試題:撰寫 PHP 函式計算兩個檔案間的相對路徑。

範例需求

  • $a = '/a/b/c/d/e.php'(基準檔案)
  • $b = '/a/b/12/34/c.php'(目標檔案)
  • 預期結果:../../12/34/c.php(從 $a 所在目錄到 $b 的相對路徑)

解法一:陣列比對法(簡潔版)

function getRelativePath($from, $to) {
    $fromParts = explode('/', $from);
    $toParts = explode('/', $to);
    // 移除檔名,保留目錄層級
    array_pop($fromParts);
    array_pop($toParts);
    // 移除開頭空元素(因絕對路徑以 / 開頭)
    if ($fromParts[0] === '') array_shift($fromParts);
    if ($toParts[0] === '') array_shift($toParts);

    $path = '';
    $max = max(count($fromParts), count($toParts));
    for ($i = 0; $i < $max; $i++) {
        if (!isset($fromParts[$i]) || !isset($toParts[$i]) || $fromParts[$i] !== $toParts[$i]) {
            // 從差異點開始:from 需往上層,to 需往下層
            $upLevels = count($fromParts) - $i;
            $path .= str_repeat('../', $upLevels);
            $path .= implode('/', array_slice($toParts, $i));
            break;
        }
    }
    return $path ?: './';
}

// 測試
$a = '/a/b/c/d/e.php';
$b = '/a/b/12/34/c.php';
echo getRelativePath($a, $b); // 輸出: ../../12/34/c.php

解法二:逐層比對法(原始碼邏輯)

function getpathinfo($a, $b) {
    $a2array = explode('/', $a);
    $b2array = explode('/', $b);
    $pathinfo = '';
    // -2 排除檔名與開頭空元素
    for ($i = 1; $i <= count($b2array) - 2; $i++) {
        $pathinfo .= ($a2array[$i] == $b2array[$i]) ? '../' : $b2array[$i] . '/';
    }
    return $pathinfo;
}

注意:此解法假設共同前綴長度固定,通用性較弱。

解法三:進階版(支援相對路徑、存在性檢查)

function GetRelativePath($file1, $file2) {
    if (!is_file($file1) || !is_file($file2)) return '路徑不合法!';
    $dir1 = explode('/', dirname($file1));
    $dir2 = explode('/', dirname($file2));
    $maxLen = max(count($dir1), count($dir2));
    $up = '';
    $down = [];
    for ($i = 0; $i < $maxLen; $i++) {
        $d1 = isset($dir1[$i]) ? $dir1[$i] : null;
        $d2 = isset($dir2[$i]) ? $dir2[$i] : null;
        if ($d1 !== $d2) {
            if ($d2 !== null) $down[] = $d2;
            if ($d1 !== null) $up .= '../';
        }
    }
    return $up . implode('/', $down) . '/' . basename($file2);
}

總結

核心邏輯:將路徑拆解為目錄陣列 → 找出共同前綴 → 基準路徑產生 ../ 回溯 → 目標路徑補上剩餘層級。實務建議使用 PHP 5.3+ 內建 realpath() 搭配 Symfony\Component\Filesystem\Path 或自行封裝通用函式。

copyright © 萬盛學電腦網 all rights reserved