I'm looking for a function that counts the number of times a string occurs within a file, I tried using $count = preg_match_all("/String/", $file, $matches);
but it returns Warning: preg_match_all() expects parameter 2 to be string, resource given
. Is there any function that allows me to do this with a file, instead of a string, or is there any way to assign a file to a string (I assume the latter would be a lot slower)?
yes:
file_get_contents()
— Reads entire file into a string
http://php.net/manual/en/function.file-get-contents.php
so for you it would be
$file = file_get_contents(PATH_TO_FILE);
$count = preg_match_all("/String/", $file, $matches);
I'm guessing you have used fopen
instead by mistake?
$count = substr_count(file_get_contents($file), $string);
Manual:
substr_count
file_get_contents
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With