LoginSignup
1
0

More than 5 years have passed since last update.

PHPでファイルパスの正規化

Last updated at Posted at 2018-06-01

問題

PHP: realpath - Manual

返り値
realpath() は、 たとえばファイルが存在しないなどの失敗時に FALSE を返します。

実装

WindowsとLinuxの両方に対応している関数が見つからなかったので書いた。

function normalizePath($path, $separator = '/') {
    if (preg_match('/^(([a-zA-Z]:)?)[\/\\\\]/', $path, $matches) !== 1) {
        return normalizePath(getcwd().$separator.$path);
    }

    return $matches[1] . array_reduce(
        preg_split('/[\/\\\\]/', ltrim($path, $matches[1]), -1, PREG_SPLIT_NO_EMPTY),
        function($absolutes, $part) use($separator) {
            if ($part === '.') return $absolutes;
            if ($part === '..') return dirname($absolutes);
            if ($absolutes === $separator) return $absolutes.$part;
            return $absolutes.$separator.$part;
        }
    );
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0