How can regular expressions be utilized in PHP to efficiently extract data from a file with varying patterns?

Regular expressions can be utilized in PHP to efficiently extract data from a file with varying patterns by defining a pattern that matches the desired data and using functions like preg_match() or preg_match_all() to extract the data based on that pattern. This allows for flexibility in extracting data from files with different formats or structures.

$file_contents = file_get_contents('data.txt');
$pattern = '/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i'; // Example pattern for extracting email addresses
if (preg_match_all($pattern, $file_contents, $matches)) {
    foreach ($matches[0] as $email) {
        echo $email . "\n";
    }
}