In the context of PHP, how can regular expressions be utilized to manipulate strings according to specific patterns?
Regular expressions in PHP can be used to search for specific patterns within strings and manipulate them accordingly. This can be useful for tasks such as extracting certain information from a string, replacing text based on a pattern, or validating input against a specific format. By using functions like preg_match(), preg_replace(), and preg_split(), developers can easily work with regular expressions to achieve their desired outcomes.
// Example: Extracting all email addresses from a string
$string = "Contact us at email@example.com or support@example.com for assistance.";
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
preg_match_all($pattern, $string, $matches);
$emailAddresses = $matches[0];
print_r($emailAddresses);