Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP searching for a string in a file

Tags:

string

php

count

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)?

like image 503
John Avatar asked May 23 '11 23:05

John


2 Answers

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?

like image 104
James Butler Avatar answered Sep 20 '22 06:09

James Butler


$count = substr_count(file_get_contents($file), $string);

Manual:
substr_count
file_get_contents

like image 22
OZ_ Avatar answered Sep 20 '22 06:09

OZ_