2015-10-26 94 views
0

我有一個巨大的文件,其中有數據行(幾乎相同長度)。我想瀏覽它們並找到某個單詞的每一個出現,然後將該單詞出現在整個行中並將其回顯到屏幕上。目前我正在使用這種方法:用PHP搜索.txt文件中的短語

$result_counter = 0; 
$result_array[1] = 'No results'; 

$search_slug = $request->input('search_slug'); 
$fp = fopen(base_path('storage\app\xas.txt'), "r"); 

while (false !== ($line = fgets($fp))) { 
    // Process $line, e.g split it into values since it is CSV. 

    $exploded = explode('-', $line); 
    $exploded = implode('', $exploded); 
    set_time_limit(30); 
    if(strpos($exploded, strtoupper($search_slug))) { 
     $result_counter++; 
     $result_array[$result_counter] = $exploded; 
    } 
} 
return view('results')->with(array('results' => $result_array, 'query' => $search_slug)); 
fclose($fp); 

逐行掃描一個巨大的文件只需要很長的時間。

你可能會問 - 你爲什麼不使用MySQL?

存在一個巨大的問題 - 我的文件長度爲250萬行,可能很快就會變大。如果我一次嘗試更新數據庫,我的服務器的所有者將禁止我的帳戶,更不用說人們將按小時查詢大部分數據庫的事實。我買不起「無限制」的服務器。我會盡快遷移到MySQL,但現在我需要一個快速解決方案。

如何使用PHP解決此問題?有沒有辦法搜索文件中的單詞出現,然後只抓取這些行?

+2

我會使用像Lucene的實際搜索索引(或任何現代當量)。一些提示在這裏〜http://stackoverflow.com/questions/2010663/lucene-with-php – Phil

+0

哦,我不知道,謝謝你的提示,我會研究它。 –

+3

也許系統調用'grep'? – fpierrat

回答

0

您可以使用正則表達式這樣^.*yourword.*$.

資源:http://www.regular-expressions.info/completelines.html

+0

無論我使用正則表達式還是strpos,都沒關係。這不是我的問題,我的問題是關於瀏覽文件時的速度。 –

+0

感謝downvoting,「*搜索與PHP * .txt文件中的短語」也「*我想瀏覽它們,並找到每個發生的某個單詞,*」 –

+0

我有我的懷疑,瓶頸來從循環播放文件。看到我上面的評論。 – Mike