0

我需要在符合特定条件的目录中找到一个文件。例如,我知道文件名以“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);
4

2 回答 2

3

我在这里为你写了一个小脚本,科菲。试试这个尺寸。

我为自己的测试更改了目录,因此请务必将其设置回您的常量。

目录内容:

  • 123-香蕉.txt
  • 123-额外的香蕉.tpl.php
  • 123-wow_this_is_cool.txt
  • 无香蕉.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().

于 2012-12-07T19:43:36.543 回答
1

您必须测试匹配是否成功。

您在循环中的代码应该是这样的:

if ($file !== "." && $file !== "..") {
    if (preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name)) {
        // $name[0] is the file name you want.
        echo $name[0];
    }
}
于 2012-12-07T19:26:37.720 回答