如何使用php扫描所有的.m文件?
可能重复:如何使用php扫描所有的.m文件?,php,file,Php,File,可能重复: 我有一个文件夹,在这个文件夹中,有许多子文件夹,但我想扫描所有的子文件夹,并扫描所有的.m文件。。。我怎么能这样做 文件如下: /MyFilePath/ /myPath.m /myPath2.m /myPath3.m /MyClasses/ /my.m /my1.m /my2.m
我有一个文件夹,在这个文件夹中,有许多子文件夹,但我想扫描所有的子文件夹,并扫描所有的.m文件。。。我怎么能这样做 文件如下:
/MyFilePath/
/myPath.m
/myPath2.m
/myPath3.m
/MyClasses/
/my.m
/my1.m
/my2.m
/my3.m
/Utilities/
/u1.m
/u2.m
/External/
/a.m
/b.m
/c.m
/Internal/
/d.m
/e.m
/f.m
/Views/
/a_v.m
/b_v.m
/c_v.m
/Controllers/
/a_vc.m
/b_vc.m
/c_vc.m
/AnotherClasses/
/anmy.m
/anmy1.m
/anmy2.m
/anmy3.m
/Networking/
/net1.m
/net2.m
/net3.m
/External/
/Internal/
/Views/
/Controllers/
您需要查看PHP文档以了解有关以下内容的详细信息: 这里有一个例子,它应该做你想做的事情。它将返回子目录中所有.m文件的数组。然后,如果您感兴趣,可以循环浏览每个文件并读取内容
<?php
function get_m_files($root = '.'){
$files = array();
$directories = array();
$last_letter = $root[strlen($root)-1];
$root = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;
$directories[] = $root;
while (sizeof($directories)) {
$dir = array_pop($directories);
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$file = $dir.$file;
if (is_dir($file)) {
$directory_path = $file.DIRECTORY_SEPARATOR;
array_push($directories, $directory_path);
} elseif (is_file($file)) {
if (substr( $file, -strlen( ".m" ) ) == ".m") {
$files[] = $file;
}
}
}
closedir($handle);
}
}
return $files;
}
?>
您可以使用如下递归函数:
function searchFiles($dir,$pattern,$recursive=false)
{
$matches = array();
$d = dir($dir);
while (false !== ($entry = $d->read()))
{
if (is_dir($d->path.$entry) && $recursive)
{
$subdir = $d->path.$entry;
$matches = array_merge($matches,searchFiles($dir,$pattern,$recursive));
}
elseif (is_file($d->path.$entry) && preg_match($pattern,$entry))
{
$matches[] = $d->path.$entry;
}
}
$d->close();
return $matches;
}
用法:
$matches = searchFiles("/mypath/","'[.]m$'i",true);
您还可以使用的一些的迭代器。一个简单的示例如下所示:
$directories = new RecursiveDirectoryIterator('path/to/search');
$flattened = new RecursiveIteratorIterator($directories);
$filter = new RegexIterator($flattened, '/\.in$/');
foreach ($filter as $file) {
echo $file, PHP_EOL;
}
更多信息(大部分不完整):
你说的“扫描所有.m文件”是什么意思?要列出.m文件还是要查看文件中的内容?.m文件可以位于您指定的任何文件夹中吗?比所有其他文件夹都好得多!另外,这不包括像file.moo
和so.m.txt
这样的文件吗?@Svish谢谢。我想我已经解决了。
$directories = new RecursiveDirectoryIterator('path/to/search');
$flattened = new RecursiveIteratorIterator($directories);
$filter = new RegexIterator($flattened, '/\.in$/');
foreach ($filter as $file) {
echo $file, PHP_EOL;
}