代码之家  ›  专栏  ›  技术社区  ›  troex

是否有与python os.path.normpath()等价的php函数?

  •  6
  • troex  · 技术社区  · 16 年前

    是否有与python等价的php函数 os.path.normpath() ?
    或者我怎样才能得到 确切地 php中的相同功能?

    2 回复  |  直到 16 年前
        1
  •  6
  •   troex    16 年前

    下面是我对php中python的posixpath.py中normpath()方法的1:1重写:

    function normpath($path)
    {
        if (empty($path))
            return '.';
    
        if (strpos($path, '/') === 0)
            $initial_slashes = true;
        else
            $initial_slashes = false;
        if (
            ($initial_slashes) &&
            (strpos($path, '//') === 0) &&
            (strpos($path, '///') === false)
        )
            $initial_slashes = 2;
        $initial_slashes = (int) $initial_slashes;
    
        $comps = explode('/', $path);
        $new_comps = array();
        foreach ($comps as $comp)
        {
            if (in_array($comp, array('', '.')))
                continue;
            if (
                ($comp != '..') ||
                (!$initial_slashes && !$new_comps) ||
                ($new_comps && (end($new_comps) == '..'))
            )
                array_push($new_comps, $comp);
            elseif ($new_comps)
                array_pop($new_comps);
        }
        $comps = $new_comps;
        $path = implode('/', $comps);
        if ($initial_slashes)
            $path = str_repeat('/', $initial_slashes) . $path;
        if ($path)
            return $path;
        else
            return '.';
    }
    

    这样就行了 确切地 与python中的os.path.normpath()相同

        2
  •  2
  •   Powerlord    16 年前

    是的, realpath 命令将返回规范化路径。它类似于python的组合版本 os.path.normpath 和 os.path.realpath .

    不过,它也将解析符号链接。我不知道如果你不想那样做你会怎么做。