【问题标题】:Find file in a directory using preg_match?使用 preg_match 在目录中查找文件?
【发布时间】: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


【解决方案1】:

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

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

目录内容:

  • 123-banana.txt
  • 123-extra-bananas.tpl.php
  • 123-wow_this_is_cool.txt
  • no-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() 匹配后这样做。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2010-10-11
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多