2012-12-07 20 views
0

我需要在符合特定條件的目錄中找到文件。例如,我知道文件名以'123-'開頭,以.txt結尾,但我不知道兩者之間的內容。使用preg_match在目錄中查找文件?

我已經啓動了獲取目錄中的文件和preg_match的代碼,但是卡住了。如何更新以找到我需要的文件?

$id = 123; 

// create a handler for the directory 
$handler = opendir(DOCUMENTS_DIRECTORY); 

// open directory and walk through the filenames 
while ($file = readdir($handler)) { 

    // if file isn't this directory or its parent, add it to the results 
    if ($file !== "." && $file !== "..") { 
    preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name); 

    // $name = the file I want 
    } 

} 

// tidy up: close the handler 
closedir($handler); 
+0

使用這個:'/ ^(123 - 。*。txt)/ i';匹配文件名稱以123開頭 - 任何內容以.txt結尾。 – phpisuber01

回答

3

我這裏寫了一個小腳本爲雅,Cofey。試試這個大小。

我改變了我自己的測試目錄,所以一定要把它設置回常量。

目錄內容:

  • 123 banana.txt
  • 123-EXTRA-bananas.tpl.php
  • 123 wow_this_is_cool.txt
  • 沒有bananas.yml

代碼:

<pre> 
<?php 
$id = 123; 
$handler = opendir(__DIR__ . '\test'); 
while ($file = readdir($handler)) 
{ 
    if ($file !== "." && $file !== "..") 
    { 
     preg_match("/^({$id}-.*.txt)/i" , $file, $name); 
     echo isset($name[0]) ? $name[0] . "\n\n" : ''; 
    } 
} 
closedir($handler); 
?> 
</pre> 

結果:

123-banana.txt 

123-wow_this_is_cool.txt 

preg_match保存其結果$name作爲一個數組,所以我們需要通過它來訪問的0鍵我第一次檢查,以後也這樣做肯定我們得到了一個與isset()匹配。

1

您必須測試比賽是否成功。

你的循環內的代碼應該是這樣的:

if ($file !== "." && $file !== "..") { 
    if (preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name)) { 
     // $name[0] is the file name you want. 
     echo $name[0]; 
    } 
}