2014-05-09 47 views
3

如何確定文件路徑是否絕對?必須在Windows和Linux上工作。如何確定文件路徑是否絕對?

+0

檢查是否有冒號':'?以'http://','https://','file:///','C:/'開頭的路徑都是絕對路徑。你也可以看看路徑是以'/'還是'〜'開始的。 –

+0

@LoganMurphy Unix不是 –

+0

你看了這個,也許很有用? http://stackoverflow.com/questions/7392274/checking-for-relative-vs-absolute-paths-urls-in-php –

回答

4

這裏我嘗試在一個單一的功能做:

function isAbsolutePath($path) { 
    if (!is_string($path)) { 
     $mess = sprintf('String expected but was given %s', gettype($path)); 
     throw new \InvalidArgumentException($mess); 
    } 
    if (!ctype_print($path)) { 
     $mess = 'Path can NOT have non-printable characters or be empty'; 
     throw new \DomainException($mess); 
    } 
    // Optional wrapper(s). 
    $regExp = '%^(?<wrappers>(?:[[:print:]]{2,}://)*)'; 
    // Optional root prefix. 
    $regExp .= '(?<root>(?:[[:alpha:]]:/|/)?)'; 
    // Actual path. 
    $regExp .= '(?<path>(?:[[:print:]]*))$%'; 
    $parts = []; 
    if (!preg_match($regExp, $path, $parts)) { 
     $mess = sprintf('Path is NOT valid, was given %s', $path); 
     throw new \DomainException($mess); 
    } 
    if ('' !== $parts['root']) { 
     return true; 
    } 
    return false; 
} 

我把這個從我的項目之一,文件名和路徑工作時,你會覺得非常有用: dragonrun1/file_path_normalizer

+1

看不到任何問題。將接受。謝謝! – mpen

+0

這是從StackOverflow答案中複製粘貼的解決方案。我更感興趣的是目前是否存在一種在StackOverflow之外建立存在的「獲勝」或「事實標準」解決方案,就像一個可以用作曲者或其他東西安裝的庫。是否有「事實標準」路徑實用程序庫? –

+0

如果你看看我上面的答案,我給出了我做的項目的鏈接,這也是通過作曲家提供的。 – Dragonaire

1

這是我想出來的:

function is_absolute_path($path) { 
    if($path === null || $path === '') throw new Exception("Empty path"); 
    return $path[0] === DIRECTORY_SEPARATOR || preg_match('~\A[A-Z]:(?![^/\\\\])~i',$path) > 0; 
} 

我認爲,涵蓋了所有的Windows possible根路徑。

+0

對於包含[wrappers](http://php.net/manual/en/wrappers.php)的路徑,它仍然會失效。嘗試'zlib:// c:/ dummy/path /'或'file:// c:/ dummy/path' – Dragonaire

+0

@Dragonaire [Node](https://nodejs.org/api/path.html#path_path_isabsolute_path)這兩個例子都會返回「false」,我認爲這是正確的答案。我們在這裏討論*文件*路徑,而不是URL。 – mpen

+0

猜你需要閱讀我給出的包裝鏈接,因爲它們與URL本身無關。你可以使用它們來實現類似於ftp的東西,但是你有file://不再那麼在流資源中創建一個本地文件,而不是一個字符串。 Node(JS)不明白PHP特定的東西的事實也不令我感到驚訝;) – Dragonaire

相關問題