How can regular expressions be utilized effectively in PHP to extract data from external sources?

Regular expressions can be used in PHP to extract specific data from external sources by defining patterns that match the desired data. This can be useful when parsing text from websites, APIs, or other sources where the data is not structured in a predictable way. By using functions like preg_match() or preg_match_all(), you can search for and extract the data that matches your specified regular expression pattern.

// Sample code to extract email addresses from a text file using regular expressions
$text = file_get_contents('sample.txt');
$pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/';
preg_match_all($pattern, $text, $matches);

foreach ($matches[0] as $email) {
    echo $email . "\n";
}