What are some common methods for extracting data from complex strings in PHP, such as email addresses?
When extracting data from complex strings like email addresses in PHP, regular expressions are commonly used to match and extract the desired information. By using regular expressions, you can define patterns that match the structure of email addresses and extract them from the input string.
// Example code to extract email addresses from a string using regular expressions
$string = "Contact us at email@example.com or support@example.com for assistance.";
// Define the regular expression pattern for matching email addresses
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
// Perform the regular expression match and store the results in the $matches array
preg_match_all($pattern, $string, $matches);
// Output the matched email addresses
foreach ($matches[0] as $email) {
echo $email . "\n";
}