What potential pitfalls can arise when using regular expressions to sanitize email headers, subjects, and messages in PHP?

Potential pitfalls when using regular expressions to sanitize email headers, subjects, and messages in PHP include incorrectly filtering valid email addresses, accidentally removing important characters or information from the email content, and creating overly complex or inefficient regex patterns that may not catch all potential threats. To solve this issue, it is recommended to use PHP's built-in functions for email validation and sanitization, such as filter_var() with the FILTER_SANITIZE_EMAIL filter for email addresses, and htmlspecialchars() for message content. These functions are specifically designed to handle email-related data securely and efficiently.

// Sanitize email address using filter_var
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Sanitize message content using htmlspecialchars
$message = htmlspecialchars($message, ENT_QUOTES);