我可以用标准来计算文本文件吗?

时间:2014-03-16 22:28:00

标签: php html arrays lines

以下代码显示我从带有条件的文本文件中选择行。 我想知道我是否可以计算这些行,希望有一个简单的方法来做,即不使用数组..... 任何帮助?

2 个答案:

答案 0 :(得分:2)

使用$count变量跟踪。
这应该有效 -

$count = 0;
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(strpos($line, $search) !== false){
    $count++;
    echo '<p> '.$line.' </p>';
  }
}
echo $count;

答案 1 :(得分:1)

我不确定我是否理解你,这是你想要的吗?

<?php
// What to look for
$search = 'red';
// Read from file
$lines = file('file.txt');
$count_lines=0;
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(strpos($line, $search) !== false)
    echo '<p> '.$line.' </p>';
    $count_lines++;
}
echo $count_lines;
?>
相关问题