我正在尋找搜索某些字符串到某些文件夾結構的最快方法。我知道我可以使用file_get_contents從文件中獲取所有內容,但我不確定是否快。也許已經有一些解決方案可以快速運行。我正在考慮使用scandir讓所有文件和file_get_contents讀取它的內容和strpos來檢查字符串是否存在。在文件夾中搜索字符串的所有文件
你認爲有更好的方法嗎?
或者也許試圖使用PHP執行與grep?
在此先感謝!
我正在尋找搜索某些字符串到某些文件夾結構的最快方法。我知道我可以使用file_get_contents從文件中獲取所有內容,但我不確定是否快。也許已經有一些解決方案可以快速運行。我正在考慮使用scandir讓所有文件和file_get_contents讀取它的內容和strpos來檢查字符串是否存在。在文件夾中搜索字符串的所有文件
你認爲有更好的方法嗎?
或者也許試圖使用PHP執行與grep?
在此先感謝!
你兩個選項是DirectoryIterator或glob:
$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 alternative至file_get_contents
。
使用目錄迭代器和foreach: http://php.net/manual/en/class.directoryiterator.php
比grep和file_get_contents更快嗎? – bla0009 2013-02-23 14:34:15
https://github.com/skfaisal93/AnyWhereInFiles – 2015-12-31 15:21:22