我正在寻找一个函数来计算字符串在文件中出现的次数,我尝试使用$count = preg_match_all("/String/", $file, $matches);但它返回Warning: preg_match_all() expects parameter 2 to be string, resource given.是否有任何函数允许我用文件而不是字符串来执行此操作,或者是否有任何方法将文件分配给字符串(我假设后者会慢得多)?
Jam*_*ler 12
是:
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);
Run Code Online (Sandbox Code Playgroud)
我猜你曾经fopen错误地使用过?
$count = substr_count(file_get_contents($file), $string);
Run Code Online (Sandbox Code Playgroud)
手动:
substr_count
file_get_contents