递归文件搜索 (PHP)
我正在尝试使用递归搜索返回指定目录中的文件。 我成功地实现了这一点,但是我想添加几行代码,以允许我指定我想要返回的某些扩展名。
例如,仅返回目录中的 .jpg 文件。
这是我的代码,
<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
foreach(new RecursiveIteratorIterator($it) as $file) {
echo $file . "<br/> \n";
}
?>
请让我知道我可以在上面的代码中添加什么来实现这一点,谢谢
I'm trying to return the files in a specified directory using a recursive search.
I successfully achieved this, however I want to add a few lines of code that will allow me to specify certain extensions that I want to be returned.
For example return only .jpg files in the directory.
Here's my code,
<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
foreach(new RecursiveIteratorIterator($it) as $file) {
echo $file . "<br/> \n";
}
?>
please let me know what I can add to the above code to achieve this, thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您应该创建一个过滤器:
You should create a filter:
试试这个,它使用允许的文件类型的数组,并且仅在数组中存在文件扩展名时才回显该文件。
您可能还会发现,可以将允许的文件类型数组传递给
RecursiveDirectoryIterator
类,并且仅返回匹配的文件。Try this, it uses an array of allowed file types and only echos out the file if the file extension exists within the array.
You may also find that you could pass an array of allowed file types to your
RecursiveDirectoryIterator
class and only return files that match.让 PHP 完成这项工作:
Let PHP do the job:
关于投票最高的答案:我创建的代码使用的函数较少,只有 3 个,
isset()
、array_flip()
、explode()
而不是 4 个函数。我测试了投票最高的答案,它比我的慢。我建议尝试一下我的:Regarding the top voted answer: I created this code which is using fewer functions, only 3,
isset()
,array_flip()
,explode()
instead of 4 functions. I tested the top voted answer and it was slower than mine. I suggest giving mine a try:这些都不适合我的情况。所以我写了这个函数,不确定效率,我只是想快速删除一些重复的照片。希望它对其他人有帮助。
唯一可以做的一点改进是,目前要使其工作,您必须在起始目录上有一个尾部正斜杠。
None of these worked for my case. So i wrote this function, not sure about efficiency, I just wanted to remove some duplicate photos quickly. Hope it helps someone else.
Only slight improvement that could be made is that currently for it to work you have to have a trailing forward slash on the start directory.
在此示例代码中;
$directory
变量设置任何路径,例如./
、'L:\folder\folder\folder'
或任何内容。 。$pattern
中设置模式文件名(可选),您可以为每个带有.jpg< 的文件添加
'/\.jpg$/'
/code> 扩展名,如果你想查找所有文件,可以使用'//'
作为这个变量。In this sample code;
$directory
variable, for example./
,'L:\folder\folder\folder'
or anythings...$pattern
optional, You can put'/\.jpg$/'
for every file with.jpg
extension, and also if you want to find all files, can just use'//'
for this variable.这是在文件夹和子文件夹中搜索的正确方法
here is the correct way to search in folders and sub folders
您可能想查看有关使用 glob() 进行类似搜索的页面:
http: //www.electrictoolbox.com/php-glob-find-files/
You might want to check out this page about using glob() for a similar search:
http://www.electrictoolbox.com/php-glob-find-files/