views:

63

answers:

1

Hi, I have a quick question.

As the title says, I'd like to find a way to count the number of lines that contain a specified string in a file, in PHP.

I know I could simply open the file and loop through all the lines and see if anything matches, but that seems kind of cumbersome. Is there a better way?

To further illustrate what I want to do, here's how it could look with awk:

awk '/KEYWORD/ {i++} END { print i }' FILE

Thanks!

+1  A: 

This hardly seems "cumbersome" to me:

$c = 0;
foreach(file($filename) as $line)
  if (strpos($line, $str) !== false) ++$c;

You might be able to get away with a regular expression, but if you truly want to count the lines (as opposed to instances), there's surely not a cleaner way (in terms of brevity and clarity) than the above method.

Edit, per the first comment:

echo substr_count(file_get_contents($filename), $str);

That should work.

konforce
I want the lines, but the format the file will be in makes it so that there is no difference if I count instances.
houbysoft
Then you could use `substr_count()` or even `count(preg_match_all())` on `file_get_contents()`. All of these methods will load the entire file into memory, which isn't advisable on large files.
konforce
Changed the accepted answer as the edit is even simpler than dvcolgan's answer. Thanks.
houbysoft