[英]How to read all files in a directory starting with specific path in PHP
我有像fm.txt fm_1.txt, fm_2.txt
这样的文件名。 运行脚本时,我需要获取以fm开头的所有文件的计数。
$files = glob(PATH_DIR.'_*.txt');
echo count($files);
显示我count
为0。
$files = glob(PATH_DIR.'*.txt');
echo count($files);
显示我数为1。
实际上有1个文件有fm.txt, fm_1.txt, fm_2.txt
。 我想第二个片段只显示fm.txt
计数,如何修改该行以获得_
文件的fm.txt
您可以使用readdir函数http://php.net/manual/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;
假设您在当前目录中具有以下结构:
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]*
。
你需要告诉glob函数你想要以fm开头的文件,所以试试这个:
glob(PATH_TO_YOUR_DIR。“fm * .txt”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.