How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in PHP

1 Answer

0 votes
// Function to simplify a Unix-style file path
function simplifyPath(string $path): string {
    $stack = [];       // Stack to hold valid directory names
    $result = "";      // Final simplified path
    $psize = strlen($path);  // Length of the input path
    $i = 0;

    // Iterate through each character in the path
    while ($i < $psize) {
        if ($path[$i] === '/') {
            $i++;
            continue;  // Skip redundant slashes
        }

        $pathpart = "";

        // Extract the next pathpart until the next slash
        while ($i < $psize && $path[$i] !== '/') {
            $pathpart .= $path[$i];
            $i++;
        }

        // Ignore current directory references
        if ($pathpart === ".") {
            continue;
        }
        // Ignore parent directory references (no popping here)
        elseif ($pathpart === "..") {
            continue;
        }
        // Valid directory name, push to stack
        else {
            array_push($stack, $pathpart);
        }
    }

    // Reconstruct the simplified path from the stack
    while (!empty($stack)) {
        $result = "/" . array_pop($stack) . $result;
    }

    // If the stack was empty, return root directory
    return $result !== "" ? $result : "/";
}

// Input path to be simplified
$inputPath = "/home//foo/../bar/./unix/";

// Call the simplifyPath function
$simplified = simplifyPath($inputPath);

// Output the result
echo "Simplified path: " . $simplified . PHP_EOL;



/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 8 by avibootz
...