计算文件中包含字符串的行数的优雅方法

发布于 2024-09-06 20:57:55 字数 238 浏览 2 评论 0原文

我有一个简单的问题。

正如标题所说,我想找到一种方法来计算 PHP 文件中包含指定字符串的行数。

我知道我可以简单地打开文件并循环遍历所有行,看看是否有匹配的内容,但这似乎有点麻烦。有更好的办法吗?

为了进一步说明我想要做什么,下面是 awk 的样子:

awk '/KEYWORD/ {i++} END { print i }' 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空心↖ 2024-09-13 20:57:55

这对我来说似乎并不“麻烦”:

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

您也许可以使用正则表达式,但如果您真的想计算行数(而不是实例),那么肯定没有更干净的方法(就简洁性和清晰度而言) )比上面的方法。

编辑,根据第一条评论:

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

那应该有效。

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.

菊凝晚露 2024-09-13 20:57:55

请注意,当使用愚蠢的大文件(例如 500MB+)运行时,file() 会阻塞。如果这在您的 Web 应用程序中很常见,例如许多并发用户计算巨大的文件大小,这将影响性能。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文