2013-02-23 79 views
6

我正在尋找搜索某些字符串到某些文件夾結構的最快方法。我知道我可以使用file_get_contents從文件中獲取所有內容,但我不確定是否快。也許已經有一些解決方案可以快速運行。我正在考慮使用scandir讓所有文件和file_get_contents讀取它的內容和strpos來檢查字符串是否存在。在文件夾中搜索字符串的所有文件

你認爲有更好的方法嗎?

或者也許試圖使用PHP執行與grep?

在此先感謝!

+0

https://github.com/skfaisal93/AnyWhereInFiles – 2015-12-31 15:21:22

回答

12

你兩個選項是DirectoryIteratorglob

$string = 'something'; 

$dir = new DirectoryIterator('some_dir'); 
foreach ($dir as $file) { 
    $content = file_get_contents($file->getPathname()); 
    if (strpos($content, $string) !== false) { 
     // Bingo 
    } 
} 

$dir = 'some_dir'; 
foreach (glob("$dir/*") as $file) { 
    $content = file_get_contents("$dir/$file"); 
    if (strpos($content, $string) !== false) { 
     // Bingo 
    } 
} 

在性能方面,你可以隨時compute the real-time speed of your code或很容易找出memory usage。對於較大的文件,您可能需要使用an alternativefile_get_contents

+0

您的解決方案檢查文件名,我需要檢查文件內容。代碼有很大的不同嗎? – bla0009 2013-02-23 14:55:55

+0

查看更新的答案 – hohner 2013-02-23 14:58:09

相關問題