substr_count issue

hi everyone,

I need to open 2 external files in order to do some calculations.

  1. how many lines of text are in each file
  2. how many lines of text contain “examplestring” for each file.

I have created an array with the filenames and a foreach loop.
Question 1 works. I have the linecount nicely displayed in html for each file.
However I’m unable to get Question 2 working. Anyone can help please?

[php]
$files= array(“namefile1”, “namefile2”);
foreach ($files as $file) {
$filename = “data/”.$file.".txt";
$handle = fopen($filename, “r”);
$linecount = 0;
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
echo substr_count($line, “examplestring”);
}
echo “

” . basename($filename, “.txt”) . ": " . PHP_EOL;
echo $linecount . “

”;
		}[/php]

Basically I should get an html output like this:

Question1

namefile1: 100
namefile2: 120

Question2

namefile1: 10
namefile2: 16

Seems like you’re close. It’s not to elegant, but basically the below should do what you’re asking.

[php]$files= array(“namefile1”, “namefile2”);
foreach ($files as $file) {
$filename = “data/”.$file.".txt";
$handle = fopen($filename, “r”);
$linecount = 0;
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
echo “

” . basename($filename, “.txt”) . ": " . PHP_EOL;
echo $linecount . “

”;
		}


		foreach ($files as $file) {
			$filename = "data/".$file.".txt";
			$handle = fopen($filename, "r");
			$stringcount = 0;
			while(!feof($handle)){
				$line = fgets($handle);				
				$stringcount += substr_count($line, "examplestring");
			}
			echo "<p>" . basename($filename, ".txt") . ": " . PHP_EOL;
			echo $stringcount . "</p>";
		
		}

[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service