realpath() without resolving symlinks?

后端 未结 3 1721
粉色の甜心
粉色の甜心 2020-12-10 14:03

I already read about realpath(), but is there a function that I can pass a base directory and a filename that would give me the following result without resolvi

3条回答
  •  死守一世寂寞
    2020-12-10 14:26

    function normalize_path($path, $pwd = '/') {
            if (!isset($path[0]) || $path[0] !== '/') {
                    $result = explode('/', getcwd());
            } else {
                    $result = array('');
            }
            $parts = explode('/', $path);
            foreach($parts as $part) {
                if ($part === '' || $part == '.') {
                        continue;
                } if ($part == '..') {
                        array_pop($result);
                } else {
                        $result[] = $part;
                }
            }
            return implode('/', $result);
    }
    

    (The question was tagged PHP at the time I wrote this.)

    Anyway, here is a regex version:

    function normalize_path($path, $pwd = '/') {
            if (!isset($path[0]) || $path[0] !== '/') {
                    $path = "$pwd/$path";
            }
            return preg_replace('~
                    ^(?P>sdotdot)?(?:(?P>sdot)*/\.\.)*
                    |(?(?:(?P>sdot)*/(?!\.\.)(?:[^/]+)(?P>sdotdot)?(?P>sdot)*/\.\.)+)
                    |(?/\.?(?=/|$))+
            ~sx', '', $path);
    }
    

提交回复
热议问题