2014-08-27 108 views
0

我想獲取包含字符串(在特定文件夾內)的文件的文件名。獲取包含字符串的文件的名稱

例如:有一個名爲「test」的文件夾。在這個文件夾中有三個文件,但其中只有一個包含字符串「hello」。現在我想用PHP返回這個文件的名字。

(所有文件都是.txt)

在此先感謝!

+4

那麼你就必須打開和讀取所有文件.. – Naruto 2014-08-27 09:27:44

+0

哎喲。這在PHP中將成爲一個計算成本很高的事情。 – TunaMaxx 2014-08-27 09:30:36

+0

這是通過控制檯:grep -nr「你的字符串123456」文件夾,告訴你哪一行所在的位置,並且在那個文件中 – WhiteLine 2014-08-27 09:31:16

回答

1
  1. 獲取所有文件名的文件夾中對於給定的延期。
  2. 順序讀取所有文件的內容。
  3. 閱讀每個文件的每一行並查找匹配「hello world」的單詞
  4. 保存包含數組中匹配的文件名。

沒有測試過,但是像下面應該工作:

$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)); 
3
  1. 掃描文件夾。
  2. 打開每個文件/讀取內容。
  3. 使用函數stristr來檢查字符串「hello」是否存在。
+1

現在你正在打開每個文件...這需要很長的時間在PHP – RichardBernards 2014-08-27 09:30:40

+1

至少這是一個真正的跨平臺解決方案 – 2014-08-27 09:31:43

+0

@RichardBernards三個文本文件不應該花太長時間才能打開。 – 2014-08-27 10:02:21

3

假設* nix的環境

下面將產生含有與所述文件名的陣列的$output變量:

$output = exec("grep -l 'hello' test/*.txt"); 
+1

你假設他使用* nix環境.. – 2014-08-27 09:31:03

+0

只要exec()可用,這是一個很好的解決方案。 – TunaMaxx 2014-08-27 09:31:10

+0

@LorenzoMarcon我已經更新了我的回答並附有您的有用評論 – RichardBernards 2014-08-27 09:33:34

相關問題