Elegant way to count the number of lines that contain a string in a file
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!
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.
be aware that file() will choke when run with stupid huge files such as 500MB+. If this is common in your web application, such as many concurrent users counting huge file sizes, this will impact on performance.
精彩评论