【发布时间】:2011-02-09 20:22:13
【问题描述】:
是否有与 Python os.path.normpath() 等效的 PHP 函数?
或者我怎样才能在 PHP 中获得完全相同相同的功能?
【问题讨论】:
是否有与 Python os.path.normpath() 等效的 PHP 函数?
或者我怎样才能在 PHP 中获得完全相同相同的功能?
【问题讨论】:
是的,realpath 命令将返回规范化路径。它类似于 Python 的 os.path.normpath 和 os.path.realpath 的组合版本。
但是,它也会解析符号链接。如果你不想要这种行为,我不确定你会怎么做。
【讨论】:
os.path.normpath() 功能的方法。这个或者没有(至少)内置函数。这取决于 OP 真正需要什么......
这是我在 PHP 中从 Python 的 posixpath.py 中 1:1 重写 normpath() 方法:
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()完全相同工作
【讨论】: