2010-05-18 139 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