2010-04-19 94 views

回答

6

這裏是我的1:1 normpath()方法的重寫從Python的posixpath.py在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()
2

是的,realpath命令將返回一個規範化的路徑。它類似於Python的os.path.normpathos.path.realpath的組合版本。

但是,它也會解析符號鏈接。如果你不想要這樣的行爲,我不確定你會怎麼做。

+0

PHP的實際路徑更像os.path.abspath()或os.path.realpath() – VolkerK 2010-04-19 19:48:38

+0

@Gordon的等價物:PHP的實際路徑更像Python的os.path.normpath和os.path的組合版本。真實路徑。 – Powerlord 2010-04-19 19:50:31

+0

我認爲這是最接近'os.path.normpath()'功能。無論是這個還是那裏都沒有(至少)內置函數。這取決於OP真正需要什麼...... – 2010-04-19 19:51:59

相關問題