2012-12-12 139 views
1

我不知道任何人都可以用一個小問題,我似乎無法修復幫助 - 我 頭此刻正轉圈圈......多個搜索詞匹配使用strpos

好吧,我有一個。包含多行信息的txt文件 - 我試圖將關鍵字 與這些行匹配,並顯示一定數量的匹配行。

我把這個腳本放在一起,雖然它的作品只匹配一行,如果 字與搜索詞的順序相同。

目前作爲一個例子:

搜索詞:

紅帽

在.txt文件

行:

這是我的Red Hat
我的帽子是紅色的
這頂帽子是綠色的
這是一條紅色的圍巾
你的紅色帽子不錯

由於劇本的那一刻,它將匹配和顯示線1,5

但是我想它匹配和顯示線1,2,5

的任何命令,但所有的單詞都必須存在以匹配。

我已經通過這裏和其他地方張貼的負荷看着我的理解是 所需要的是爆炸的字符串,然後搜索每個字在一個循環中,但 我不能得到那個工作,儘管他們嘗試一些不同因爲它只是多次返回同一行的 。

之前,我輸了,我所剩下的東西發:-)

這裏是我目前使用的代碼任何幫助,將不勝感激 - 搜索變量已經 集:

<?php 
rawurldecode($search); 
$search = preg_replace('/[^a-z0-9\s]|\n|\r/',' ',$search); 
$search = strtolower($search); 
$search = trim($search); 

$lines = file('mytextfile.txt') or die("Can't open file"); 
shuffle($lines); 

$counter = 0; 

// Store true when the text is found 
$found = false; 

foreach($lines as $line) 
{ 

    if(strpos($line, $search) !== false AND $counter <= 4) 
    { 
    $found = true; 
    $line = '<img src=""> <a href="">'.$line.'</a><br>'; 


    echo $line; 
    $counter = $counter + 1; 

    } 

} 

// If the text was not found, show a message 
if(!$found) 
{ 
    echo $noresultsmessage; 
} 

?> 

謝謝提前爲任何幫助 - 仍然在學習:-)

回答

1

這裏是我的代碼:

$searchTerms = explode(' ', $search); 
$searchCount = count($searchTerms); 
foreach($lines as $line) 
{ 
    if ($counter <= 4) { 
     $matchCount = 0; 
     foreach ($searchTerms as $searchWord) { 
      if (strpos($line, $searchWord) !== false) { 
       $matchCount +=1; 
      } else { 
       //break out of foreach as no need to check the rest of the words if one wasn't found 
       continue; 
      } 
     } 
     if ($matchCount == $searchCount) { 
      $found = true; 
      $line = '<img src=""> <a href="">'.$line.'</a><br>'; 
      echo $line; 
      $counter = $counter + 1; 
     } 

    } 
} 
+0

哇!非常感謝您的快速回復 - 真正有用的是我的頭幾個小時 - 我發現的其中一件事是,我的替代品是我的工作不正常,這導致了問題:-(如果我可以問還有一個問題 - 如果沒有找到結果,我會在哪裏輸出信息輸出到屏幕上?我從評論中想到,它將在繼續聲明的周圍,但似乎並不正確?再次感謝! – onelove

+0

@onelove你有它的同樣位置;這只是取代你在代碼中使用的'foreach' – ernie

+0

@ ernie - 啊明白 - 現在所有的工作都應該如此 - 非常感謝 - 你是明星! – onelove