How can PHP be used to count occurrences of specific strings in a log file and increment a counter accordingly?

To count occurrences of specific strings in a log file using PHP, you can read the contents of the log file line by line and use a regular expression to search for the specific strings. For each match found, you can increment a counter to keep track of the occurrences.

<?php
$logFile = 'example.log';
$searchStrings = ['error', 'warning', 'info'];
$counter = array_fill_keys($searchStrings, 0);

$handle = fopen($logFile, 'r');
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        foreach ($searchStrings as $string) {
            if (preg_match("/$string/", $line)) {
                $counter[$string]++;
            }
        }
    }

    fclose($handle);

    // Output the results
    foreach ($counter as $string => $count) {
        echo "Occurrences of '$string': $count\n";
    }
} else {
    echo "Error opening the log file.";
}
?>