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.

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>';
?>
Member Avatar for diafol

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

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

Regards

Both examples work like a charm.

Thank you again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.