How can regular expressions be utilized in PHP to extract and manipulate text from a file, as shown in the provided code snippet?

Regular expressions can be used in PHP to search for specific patterns in text files and extract or manipulate the desired information. In the provided code snippet, the preg_match_all function is used to search for a specific pattern in the $text variable and extract all matching occurrences into the $matches array. This allows for easy manipulation or extraction of text based on a defined pattern.

<?php
$file = 'example.txt';
$text = file_get_contents($file);

// Define the pattern to search for
$pattern = '/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i';

// Search for the pattern in the text and store all matches in $matches
preg_match_all($pattern, $text, $matches);

// Output all email addresses found in the file
foreach ($matches[0] as $email) {
    echo $email . "\n";
}
?>