PHP中有没有与Python的os.path.normpath()等效的函数?

6 投票
2 回答
1788 浏览
提问于 2025-04-15 21:47

有没有一个和Python的 os.path.normpath() 功能一样的PHP函数?
或者我该怎么在PHP中实现完全相同的功能呢?

2 个回答

2

是的,realpath 这个命令会返回一个标准化的路径。它的功能有点像Python中的 os.path.normpathos.path.realpath 的结合版。

不过,它还会处理符号链接。如果你不想要这种效果,我就不太清楚该怎么做了。

6

这是我把Python的posixpath.py中的normpath()方法用PHP重新写的一模一样的版本:

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()完全一样

撰写回答