user1634119
user1634119

Reputation: 21

Count specific lines in text file

How to count specific lines in a text file depending on a particular variable in that line.

For example i need to count the lines of a text file only containing for instance $item1 or $item2 etc.

Upvotes: 0

Views: 2170

Answers (3)

complex857
complex857

Reputation: 20753

Sounds like you need something like what grep -c do in the shell, try something like this:

$item1 = 'match me';
$item2 = 'match me too';

// Thanks to @Baba for the suggestion:
$match_count = count(
    preg_grep(
         '/'.preg_quote($item1).'|'.preg_quote($item2).'/i',
         file('somefile_input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
    )
);

// does the same without creating a second array with the matches
$match_count = array_reduce(
    file('somefile_input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
    function($match_count, $line) use ($item1, $item2) {  
        return 
            preg_match('/'.preg_quote($item1).'|'.preg_quote($item2).'/i', $line) ?
            $match_count + 1 : $match_count;
    }
);

The above code sample uses the file() function to read the file into an array (splitted by lines), array_reduce() to iterate that array and preg_match() inside the iteration to see if a line matched (the /i at the end makes it case-insensitive).

You could use a foreach as well too.

Upvotes: 2

alexdeloy
alexdeloy

Reputation: 208

Read your file line by line and use strpos to determine if a line contains a specific string/item.

$handle = fopen ("filename", "r");
$counter = 0;
while (!feof($handle))
{
  $line = fgets($handle);
  // or $item2, $item3, etc.
  $pos = strpos($line, $item);
  if ($pos !== false)
  {
    $counter++
  }
}
fclose ($handle);

Upvotes: 1

sascha
sascha

Reputation: 4690

This code reads file.php and counts only lines containing '$item1' or '$item2'. The check itself could be finetuned, since you have to add a new stristr() for every word you want to check.

<?php

$file = 'file.php';

$fp = fopen($file, 'r');
$size = filesize($file);
$content = fread($fp, $size);

$lines = preg_split('/\n/', $content);

$count = 0;
foreach($lines as $line) {
    if(stristr($line, '$item1') || stristr($line, '$item2')) {
        $count++;
    }
}
echo $count;

Upvotes: 1

Related Questions