How can regular expressions be used in PHP to manipulate email headers for forwarding?

Regular expressions can be used in PHP to manipulate email headers for forwarding by extracting specific information such as the sender's email address or subject line. This can be useful for customizing the forwarded email or adding additional information before sending it to another recipient.

// Example code to extract sender's email address from email headers for forwarding

$email_headers = "From: John Doe <johndoe@example.com>\r\n";
$pattern = '/From: (.*) <(.*)>/'; // Regular expression pattern to extract sender's email address
preg_match($pattern, $email_headers, $matches);

$sender_name = $matches[1];
$sender_email = $matches[2];

// Forward email with extracted sender's email address
$forwarded_email_headers = "From: Forwarded Email <forwarded@example.com>\r\n";
$forwarded_email_headers .= "X-Original-Sender: $sender_email\r\n";

// Send forwarded email
mail('recipient@example.com', 'Forwarded Email', 'Hello, this is a forwarded email.', $forwarded_email_headers);