如何从PHP中的特定路径开始读取目录中的所有文件



我有像 fm.txt fm_1.txt, fm_2.txt这样的文件名。运行脚本时,我需要从FM开始获取所有文件的计数。

$files = glob(PATH_DIR.'_*.txt');
echo count($files);

向我展示0。

count
$files = glob(PATH_DIR.'*.txt');
echo count($files);

显示我的数量为1。

实际上有3个文件假设fm.txt, fm_1.txt, fm_2.txt。我猜第二个片段仅显示fm.txt计数,如何修改该行以使用_ Too

获取文件cont

您可以使用readdir函数http://php.net/manual/enual/en/function.readdir.php

$count = 0;
if ($handle = opendir(PATH_DIR)) {
    while (false !== ($entry = readdir($handle))) {
        if ( strpos($entry, 'fm') === 0 ){
            ++$count;
        }
    }
    closedir($handle);
}
echo $count;

您需要告诉Glob函数您想要以FM开头的文件,因此请尝试以下操作:

glob(path_to_your_dir。" fm*.txt")

假设您在当前目录中具有以下结构:

test.php
test
├── fm_1.txt
├── fm_2.txt
└── fm.txt

test.php

<?php
$dir = __DIR__ . '/test';
$files = glob("${dir}/fm{,_[0-9]*}.txt", GLOB_BRACE);
var_dump($files);

然后php test.php将产生类似于以下的输出:

array(3) {
  [0]=>
  string(28) "/home/ruslan/tmp/test/fm.txt"
  [1]=>
  string(30) "/home/ruslan/tmp/test/fm_1.txt"
  [2]=>
  string(30) "/home/ruslan/tmp/test/fm_2.txt"
}

由于支架扩展而导致的Glob Expressoin fm{,_[0-9]*}.txt扩展到以下模式:

  • fm.txt
  • fm_[0-9]*.txt

由于括号内有两个项目:一个空值和_[0-9]*

最新更新