Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php scandir-->;搜索文件/目录_Php - Fatal编程技术网

php scandir-->;搜索文件/目录

php scandir-->;搜索文件/目录,php,Php,我没问就找遍了,但运气不好 我正在为自己寻找一个简单的脚本,我可以搜索文件/文件夹。在php手册中找到了这个代码片段(我想我需要这个),但它不适合我 “正在寻找一种使用掩码搜索文件/目录的简单方法。下面是这样一个函数 默认情况下,此函数将在内存中保留scandir()结果,以避免对同一目录进行多次扫描。” 谢谢你的帮助 Peter尝试使用glob()如果您只想搜索文件,可以使用以下代码段: <?php $s = $get['s']; $e = ".htm"

我没问就找遍了,但运气不好

我正在为自己寻找一个简单的脚本,我可以搜索文件/文件夹。在php手册中找到了这个代码片段(我想我需要这个),但它不适合我

“正在寻找一种使用掩码搜索文件/目录的简单方法。下面是这样一个函数

默认情况下,此函数将在内存中保留scandir()结果,以避免对同一目录进行多次扫描。”


谢谢你的帮助


Peter

尝试使用
glob()

如果您只想搜索文件,可以使用以下代码段:

    <?php   
    $s = $get['s'];
    $e = ".htm";
    $folders = array("data1", "data2", "data3");
    $files = array(); // nothing needed here. anything in this array will be showed as a search result.
    for($i=0;$i<=count($folders)-1;$i++) {
        $glob = glob($folders[$i]);
        $files = array_merge($files, $glob[$i]);
    }
    echo "Search - $s<br><br>";
    if(count($files) == 1) {
        echo "<li><a href='$files[0]'>".heir($files[0])."</a></li>";
    }
    if(count($files) != 1) {
        for($i=0;$i<=count($files)-1;$i++) {
            echo "<li><a href='$files[$i]'>".heir($files[$i])."</a></li>";  
        }
    }
    if(count($files) == 0) {
        echo "Sorry, no hits.";
    }
?>

公认的答案确实不错,但它让我想起了岩石上的Spl迭代器。Fabien Povertier解释了他是如何在symfony中创建Finder类的:

我也使用他的finder类,它们有一个非常好的链接接口

  • 5.3+独立版本(来自sf2):
示例:

use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()->in(__DIR__);

foreach ($finder as $file) {
   print $file->getRealpath()."\n";
}
还有..

$finder->files()->name('*.php');
// or 
$finder->files()->size('>= 1K')->size('<= 2K');
$finder->date('since yesterday');

文档可在此处找到:

感谢您的回答,Artefactor-s解决方案对我很好,但是!没有regex有类似的解决方案吗?或者,当我只想搜索带/不带掩码的文件名时,正则表达式是什么?示例:stackoverflow.zip,我想搜索“overflow”,或“stack”,或“stackoverflow”。。。非常感谢你!为此,您只需要正则表达式
overflow
stack
stackoverflow
。这三个将匹配“stackoverflow.zip”。你可以用这种简单的方式使用正则表达式,你只需要小心地转义有特殊含义的字符。太简单了!!多谢各位+这是一个很好且有效的方法。这个问题有点离题,但你能在这里分享一下你对我的问题的看法吗
use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()->in(__DIR__);

foreach ($finder as $file) {
   print $file->getRealpath()."\n";
}
$finder->files()->name('*.php');
// or 
$finder->files()->size('>= 1K')->size('<= 2K');
$finder->date('since yesterday');
class sfException extends Exception { }