Skip to content
PHP Logo

What are some best practices for counting and storing specific lines of text based on certain keywords in PHP?

When counting and storing specific lines of text based on certain keywords in PHP, one approach is to read the text line by line and check for the presence of the keyword in each line. If the keyword is found, you can increment a counter and store the line in an array or variable for further processing. This can be achieved using a combination of file handling functions and string manipulation in PHP.

php
<?php

// Open the text file for reading
$filename = "example.txt";
$file = fopen($filename, "r");

// Initialize counter and array to store lines
$keyword = "specific_keyword";
$counter = 0;
$lines = [];

// Read the file line by line
while (!feof($file)) {
    $line = fgets($file);
    
    // Check if the keyword is present in the line
    if (strpos($line, $keyword) !== false) {
        $counter++;
        $lines[] = $line;
    }
}

// Close the file
fclose($file);

// Output the results
echo "Total lines with keyword '$keyword': $counter\n";
echo "Lines with keyword '$keyword':\n";
foreach ($lines as $line) {
    echo $line;
}

?>