0

I know that you can count the number of lines with

$record = file($data_file);
rsort($record);
$total_lines = count($record);
echo $total_lines;

Is there a way to count only lines with certain words and get a total?

for example I have a flat file with
|~|opel|~|red|~|doors 4|~|
|~|opel|~|red|~|doors 2|~|
|~|opel|~|blue|~|doors 4|~|
|~|opel|~|white|~|doors 2|~|
|~|opel|~|red|~|doors 4|~|
|~|opel|~|white|~|doors 4|~|

What I'm trying to do is get a total of only eg
- blue
- or red and white
- or blue and white

Any help would be great.

2
Contributors
4
Replies
8
Views
6 Years
Discussion Span
Last Post by Coderunner
0

Somebody already sent me the solution so problem solved!

<?php
$record = file($data_file);
rsort($record);
$red = 0;
$white = 0;
$blue = 0;
foreach ($record as $line) {
   if (strpos($line, 'red') !== false) $red++;
   if (strpos($line, 'white') !== false) $white++;
   if (strpos($line, 'blue') !== false) $blue++;
}
echo 'red:' . $red . ' pieces<br>';
echo 'white:' . $white . ' pieces<br>';
echo 'blue:' . $blue . ' pieces<br>';
?>

Edited by Coderunner: n/a

1

Also this:

$str = file_get_contents($file);
$array = array("blue","red","white"); //you can get this from a form query, so it doesn't have to be hardcoded like the example you supplied.
foreach($array as $r){
	preg_match_all("/\|$r\|/i",$str,$out);
	echo $r . " = " . count($out[0]) . "<br />";
}

Another example:

$str = file_get_contents($file);
$array = array("blue","red","white");
$label = implode(" OR ",$array);
$r = implode("\|)|(\|",$array);
preg_match_all("/(\|$r\|)/i",$str,$out);
echo $label . " = " . count($out[0]);

outputs:

blue OR red OR white = 6

Edited by diafol: n/a

0

Thank you very much for your contribution ardav.
I'll check it out.

Regards

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.