PHP: realpath() for non-existing path

By

in

The php method realpath() can transform the string format of a path into a real path. Means, a path string like:

Plaintext
/Users/mathias/data/../projects/website

will become:

Plaintext
/Users/mathias/projects/website

But this only works, if the path really exists. For non-existing paths, this function cannot be used. To get the same functionality, the following function can be used:

PHP
/**
 * Get normalized path, like realpath() for non-existing path or file
 *
 * @param string $path path to be normalized
 * @return false|string|string[]
 */
public function normalizePath(string $path)
{
    return array_reduce(explode('/', $path), function($a, $b) {
        if ($a === null) {
            $a = "/";
        }
        if ($b === "" || $b === ".") {
            return $a;
        }
        if ($b === "..") {
            return dirname($a);
        }

        return preg_replace("/\/+/", "/", "$a/$b");
    });
}


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *