PHP searches for a string in a file

I am looking for a function that counts the number of lines in a file, I tried to use $count = preg_match_all("/String/", $file, $matches); , but 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 a way to assign a file to a string (I assume the latter will be much slower)?

+6
source share
2 answers

Yes

file_get_contents() - Reads the entire file into a string

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

so for you it will be

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

I assume you used fopen instead by mistake?

+11
source
 $count = substr_count(file_get_contents($file), $string); 

Guide:
substr_count
file_get_contents

+8
source

Source: https://habr.com/ru/post/888865/


All Articles