How can preg_match_all be used effectively in PHP to extract specific data from a string using regex?

To extract specific data from a string using preg_match_all in PHP, you need to define a regular expression pattern that matches the data you want to extract. Then, use preg_match_all function to search the string for all occurrences of the pattern and store the results in an array. Finally, you can access the extracted data from the array for further processing.

$string = "Hello, my email is john.doe@example.com and my phone number is 123-456-7890.";
$pattern = '/[\w\.-]+@[\w\.-]+\.\w+/'; // Regular expression pattern to match email addresses

preg_match_all($pattern, $string, $matches);

// Extracted email addresses will be stored in $matches[0]
foreach ($matches[0] as $email) {
    echo $email . "\n";
}