2012-01-12 73 views
0

我可以在下面的代碼中添加什麼來過濾使用數組中的關鍵字返回的結果?使用關鍵字在PHP中過濾數組?

發送關鍵字並進行功能調用的代碼位於Javasript中。

下面的代碼打開一個文件,使用請求獲取指針,打開文件找到指針,並從指針到文件結尾檢索所有日誌行。然後將其格式化爲JSON對象併發送回Javacript。

function tail(){ 
    $keywords = json_decode($_REQUEST['keywords']); 

    $file = "/path/to/the/log.log"; 
    $handle = fopen($file, "r"); 
    clearstatcache();  

    if ($_REQUEST['pointer'] == '') { 
     fseek($handle, -1024, SEEK_END); 
    } else { 
     fseek($handle, $_REQUEST['pointer']); 
    } 

    while ($buffer = fgets($handle)) { 
     $log .= $buffer . "<br />\n"; 
    } 



    $output = array("pointer" => ftell($handle), "log" => $log); 
    fclose($handle); 

    echo json_encode($output); 
} 

請告訴我如何使用關鍵字數組中的關鍵字過濾檢索到的數據。

+0

你說的「過濾的意思按關鍵字'?你想看看日誌的一行是否包含某個單詞? – 2012-01-12 20:41:48

+0

是的......如果收到的行包含任何關鍵字,那麼我想保留該行並放棄其他任何不包含任何關鍵字的行。 – amlane86 2012-01-12 20:43:02

回答

2

你可能分裂的每一個空間的線,並檢查每一個字對所提供的關鍵字:

while ($buffer = fgets($handle)) { 
    $words = explode(' ', $buffer); 
    foreach ($words as $word) { 
    if (in_array($word, $keywords)) { 
     $log .= $buffer . "<br />\n"; 
     break; 
    } 
    } 
} 

或覈對讀線每個關鍵字:

while ($buffer = fgets($handle)) { 
    foreach ($keywords as $keyword) { 
    if (strstr($buffer, $keyword)) { 
     $log .= $buffer . "<br />\n"; 
     break; 
    } 
    } 
} 
1

你讀的循環改成這樣:

while ($buffer = fgets($handle)) { 
    foreach ($keywords as $kw) { // Loop keywords 
     if (strpos($buffer, $kw) !== FALSE) { // Search for this keyword 
      // If we get here, we found a keyword 
      $log .= $buffer . "<br />\n"; 
      break; 
     } 
    } 
} 

如果你想在不區分大小寫的方式來搭配,你可以使用stripos()代替。

相關問題