What is the purpose of using regex in PHP and what are some common pitfalls when implementing it?

Using regex in PHP allows for pattern matching and manipulation of strings based on specific criteria. Common use cases include validating input, searching for specific patterns within a string, and extracting data from a string. However, some common pitfalls when implementing regex in PHP include not properly escaping special characters, inefficient patterns that can lead to performance issues, and not handling edge cases or unexpected input.

// Example of using regex in PHP to validate an email address
$email = "example@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";
}