【发布时间】:2012-12-07 19:17:42
【问题描述】:
我需要在目录中找到一个符合特定条件的文件。例如,我知道文件名以 '123-' 开头,以 .txt 结尾,但我不知道两者之间是什么。
我已经开始编写代码来获取目录和 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);
【问题讨论】:
-
使用这个:
/^(123-.*.txt)/i;匹配文件名以 123- 开头的任何内容,并以 .txt 结尾。
标签: php directory while-loop preg-match opendir