How can regular expressions be utilized in PHP to efficiently parse and extract data from text files, such as in the provided example?

Regular expressions can be utilized in PHP to efficiently parse and extract data from text files by defining patterns to match specific strings or characters within the file. This allows for targeted extraction of relevant information without the need for manual parsing. In the provided example, regular expressions can be used to extract email addresses from a text file.

<?php

// Read the contents of the text file
$file_contents = file_get_contents('example.txt');

// Define the regular expression pattern to match email addresses
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';

// Use preg_match_all to extract all email addresses matching the pattern
preg_match_all($pattern, $file_contents, $matches);

// Output the extracted email addresses
foreach ($matches[0] as $email) {
    echo $email . "\n";
}

?>