我想獲取包含字符串(在特定文件夾內)的文件的文件名。獲取包含字符串的文件的名稱
例如:有一個名爲「test」的文件夾。在這個文件夾中有三個文件,但其中只有一個包含字符串「hello」。現在我想用PHP返回這個文件的名字。
(所有文件都是.txt)
在此先感謝!
我想獲取包含字符串(在特定文件夾內)的文件的文件名。獲取包含字符串的文件的名稱
例如:有一個名爲「test」的文件夾。在這個文件夾中有三個文件,但其中只有一個包含字符串「hello」。現在我想用PHP返回這個文件的名字。
(所有文件都是.txt)
在此先感謝!
沒有測試過,但是像下面應該工作:
$data = glob(FOLDER . "*.txt");
// filter
$filter = array();
// read contents of all files
for($i=0; $i<count($data); $i++) {
$file_path = $data[$i];
// open file in read-only mode
$fp = fopen($file, 'r');
// read file data
$file_data = fread($fp, filesize($file_path));
// close file handle
fclose($fp);
// make sure we catch CR-only line endings.
$file_data = str_replace("\r", "\n", $file_data);
// match using regexp
if(preg_match('/(hello world)/im', $file_data)) {
$file_name = basename($data[$i]);
array_push($filter, $file_name);
}
}
// output filtered file names
echo nl2br(print_r($filter, TRUE));
現在你正在打開每個文件...這需要很長的時間在PHP – RichardBernards 2014-08-27 09:30:40
至少這是一個真正的跨平臺解決方案 – 2014-08-27 09:31:43
@RichardBernards三個文本文件不應該花太長時間才能打開。 – 2014-08-27 10:02:21
假設* nix的環境
下面將產生含有與所述文件名的陣列的$output
變量:
$output = exec("grep -l 'hello' test/*.txt");
你假設他使用* nix環境.. – 2014-08-27 09:31:03
只要exec()可用,這是一個很好的解決方案。 – TunaMaxx 2014-08-27 09:31:10
@LorenzoMarcon我已經更新了我的回答並附有您的有用評論 – RichardBernards 2014-08-27 09:33:34
那麼你就必須打開和讀取所有文件.. – Naruto 2014-08-27 09:27:44
哎喲。這在PHP中將成爲一個計算成本很高的事情。 – TunaMaxx 2014-08-27 09:30:36
這是通過控制檯:grep -nr「你的字符串123456」文件夾,告訴你哪一行所在的位置,並且在那個文件中 – WhiteLine 2014-08-27 09:31:16