2010-05-18 93 views
5

我搜索之前,我问,没有幸运..php scandir - >搜索文件/目录

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

“正在寻找一种简单的方法来搜索使用掩模的文件/目录。这里有这样的功能。

默认情况下,该功能会在内存中保存SCANDIR()的结果,以避免scaning多次为同一个目录。“

<?php 
function sdir($path='.', $mask='*', $nocache=0){ 
    static $dir = array(); // cache result in memory 
    if (!isset($dir[$path]) || $nocache) { 
     $dir[$path] = scandir($path); 
    } 
    foreach ($dir[$path] as $i=>$entry) { 
     if ($entry!='.' && $entry!='..' && fnmatch($mask, $entry)) { 
      $sdir[] = $entry; 
     } 
    } 
    return ($sdir); 
} 
?> 

感谢您的帮助,

彼得

回答

3
$a = new RegexIterator(
    new RecursiveIteratorIterator(
     new RecursiveDirectoryIterator('DIRECTORY HERE') 
    ), 
    '/REGEX HERE/', 
    RegexIterator::MATCH 
); 

foreach ($a as $v) { 
    echo "$v\n"; //$v will be the filename 
} 
+0

感谢您的答案,Artefacto-S解决方案是为我好,但是!有没有正则表达式类似的解决方案?或者什么是正则表达式,当我只想使用/不使用掩码搜索文件名时? 例如:stackoverflow.zip,我想搜索“溢出”或“堆栈”或“计算器”... 非常感谢! – Peter 2010-05-21 15:49:06

+1

为此,您只需要正则表达式'overflow','stack'和'stackoverflow'。这三个匹配“stackoverflow.zip”。你可以用这种简单的方式使用正则表达式,你只需要小心地转义具有特殊含义的字符。 – Artefacto 2010-05-21 16:38:56

+0

太简单了!非常感谢你! – Peter 2010-05-21 16:49:21

0

我,你只是想搜索一个文件,你可以使用这个片段:

<?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."; 
    } 
?> 
0

接受的答案非常好,但它让我想到了岩石上的Spl迭代器。法比安斯基Potencier解释了他如何在symfony中创建的搜索类在这里:

http://fabien.potencier.org/article/43/find-your-files

我也用他的取景器类,他们有一个非常漂亮的链式接口。

实施例:

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'); 

Documentat离子:http://symfony.com/doc/2.0/cookbook/tools/finder.html

从sf1.4框架的PHP5.2 +版本: http://svn.symfony-project.com/branches/1.4/lib/util/sfFinder.class.php

这个版本略有不同,少花哨,但也做了工作。你需要创建一个sfException类,它只是与symfony框架搭配。您可以创建自己的sfException类:

class sfException extends Exception { } 

文档可以在这里找到:http://www.symfony-project.org/cookbook/1_2/en/finder