What is the purpose of using preg_match in PHP and what are some potential pitfalls when using it?

The purpose of using preg_match in PHP is to perform a regular expression match on a string. This function allows you to search a string for a specific pattern, providing a powerful tool for string manipulation and validation. However, some potential pitfalls when using preg_match include incorrect regular expressions leading to unexpected results, inefficient patterns causing performance issues, and potential security vulnerabilities if user input is not properly sanitized.

// Example of using preg_match to validate an email address
$email = "john.doe@example.com";

if(preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
    echo "Valid email address";
} else {
    echo "Invalid email address";
}