2011-05-23 87 views
6

我正在尋找一個函數來計算一個文件中字符串出現的次數,我嘗試使用$count = preg_match_all("/String/", $file, $matches);,但它返回Warning: preg_match_all() expects parameter 2 to be string, resource given。有沒有什麼函數可以讓我用文件而不是字符串來做到這一點,或者有什麼辦法將文件分配給字符串(我認爲後者會慢很多)?PHP搜索文件中的字符串

+1

你需要一個字符串值傳遞給第二個參數。也許你可以這樣做:'file_get_contents($ filename)'這個參數。 – 2011-05-23 23:16:27

回答

11

是:

file_get_contents() - 將整個文件讀入一個字符串

http://php.net/manual/en/function.file-get-contents.php

所以對你來說會是

$file = file_get_contents(PATH_TO_FILE); 
$count = preg_match_all("/String/", $file, $matches); 

我猜你有使用fopen ins tead錯誤?

+0

感謝felix,我的懶惰 – 2011-05-23 23:23:48

+0

是的,我一直在使用'fopen',但'file_get_contents'正是我所需要的。謝謝。 – John 2011-05-23 23:28:03