2013-02-13 57 views
0

好吧,所以我試圖列出PHP中的文本文件,我需要它們包含任何數量的一個變量$words_to_match ='spaghetti'並回顯鏈接。正如你所看到的,文本文件中充滿了字符串(或者每個字符串都是一個字符串)。搜索整個文檔,而不是按行php

這裏是我的代碼:

if($_POST["Confirmed"]=='') 
{ 
    echo "You need to enter something to search!"; 
} 
else 
{ 
    $path_to_check = 'Confirmed/'; 
    $words_to_match = $_POST["Confirmed"];//Checks the form from the last page 

    foreach(glob($path_to_check.'*.txt') as $filename) 
     { 
      foreach(file($filename) as $fli=>$fl) // Not sure what to put here. 
       { 
        if (stristr($fl,$words_to_match) !== false) //Or here. 
        { 
         echo '<a href="'.$filename.'">'.$filename.'</a><br />'; 
         } 
        } 
       } 
      } 

我不知道要放什麼東西在說foreach(file($filename) as $fli=>$fl)或者if (stristr($fl,$words_to_match) !== false)現場。我很確定第二個是正確的。 當我搜索包含多行spaghetti的文件時,它會顯示幾個相同的文件。如果有3行spaghetti,則有3個文件 - 我只想要列出該文件中的一個,即使該文件中有大量的spaghetti。我的理論是,它逐行讀取文件,並給出其中包含spaghetti的所有行的輸出。

回顧一下,我想使它成爲一個列出的文件,而不是多少行包含作爲文件列出的字符串。

任何想法?

順便說一句,我正在使用PHP 5.3的標準GoDaddy託管帳戶。

+0

'$ words_to_check' ='$ words_to_match' – 2013-02-13 23:33:25

回答

0

爲什麼不乾脆:

foreach(glob(...) as $filename) { 
    if(stripos(file_get_contents($filename),$words_to_check) !== false) { 
     // word is present. 
    } 
} 
+0

WOW ......我從來沒有想到這一點。並感謝您的回覆如此之快!有效。我馬上測試了它,現在已經在我的網頁上了!再次感謝! – 2013-02-13 23:52:51