How can regular expressions be effectively used to extract and manipulate email addresses in PHP?
Regular expressions can be effectively used in PHP to extract and manipulate email addresses by using the preg_match_all function to search for email patterns within a given string. By defining a regular expression pattern that matches email addresses, we can easily extract and manipulate email addresses from a text. This can be helpful for tasks such as validating email addresses, extracting email addresses from a larger text, or replacing email addresses with a placeholder.
<?php
// Sample text containing email addresses
$text = "Contact us at email@example.com or support@example.com for assistance.";
// Define a 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 from the text
preg_match_all($pattern, $text, $matches);
// Output the extracted email addresses
foreach ($matches[0] as $email) {
echo $email . "\n";
}
?>