How can PHP be used to search for and highlight specific words in a text file without affecting HTML tags?

When searching for specific words in a text file using PHP, we need to ensure that we do not accidentally affect any HTML tags present in the file. One way to achieve this is by reading the file line by line, using regular expressions to search for the specific words while ignoring any content within HTML tags. We can then highlight the words by wrapping them in a span tag with a CSS class for styling.

<?php
// Open the text file for reading
$file = fopen('example.txt', 'r');

// Define the specific word to search for
$word = 'example';

// Read the file line by line
while (!feof($file)) {
    $line = fgets($file);
    
    // Use preg_replace to search for the word outside of HTML tags and highlight it
    $highlighted_line = preg_replace("/(?<!<[^>]*)\b($word)\b(?![^<]*>)/i", '<span class="highlight">$1</span>', $line);
    
    // Output the highlighted line
    echo $highlighted_line;
}

// Close the file
fclose($file);
?>