How to Validate Email Using Regex in PHP: Simple Guide
To validate an email in PHP using
regex, use the preg_match function with a pattern that matches the email format. For example, preg_match('/^[\w.-]+@[\w.-]+\.\w+$/', $email) returns true if the email is valid.Syntax
The basic syntax to validate an email using regex in PHP is:
preg_match(pattern, subject): Checks if thesubjectmatches thepattern.pattern: A regex string that defines the email format rules.subject: The email string you want to validate.
The regex pattern usually checks for allowed characters before and after the @ symbol and a valid domain.
php
$email = 'example@test.com'; if (preg_match('/^[\w.-]+@[\w.-]+\.\w+$/', $email)) { echo 'Valid email'; } else { echo 'Invalid email'; }
Output
Valid email
Example
This example shows how to check if an email is valid using regex in PHP. It prints "Valid email" if the email matches the pattern, otherwise "Invalid email".
php
<?php $email = 'user.name123@example-domain.com'; $pattern = '/^[\w.-]+@[\w.-]+\.\w+$/'; if (preg_match($pattern, $email)) { echo 'Valid email'; } else { echo 'Invalid email'; } ?>
Output
Valid email
Common Pitfalls
Common mistakes when validating emails with regex in PHP include:
- Using too simple patterns that allow invalid emails like
user@@domain.com. - Using overly complex regex that rejects valid emails.
- Not escaping special characters properly in the regex.
- Ignoring built-in PHP filters that can simplify validation.
For better validation, consider using filter_var($email, FILTER_VALIDATE_EMAIL) which handles many edge cases.
php
<?php // Wrong: allows multiple @ symbols $wrong_pattern = '/^[\w.-]+@+[\w.-]+\.\w+$/'; // Right: single @ symbol $right_pattern = '/^[\w.-]+@[\w.-]+\.\w+$/'; $email = 'user@@domain.com'; if (preg_match($wrong_pattern, $email)) { echo 'Wrong pattern: Valid email\n'; } else { echo 'Wrong pattern: Invalid email\n'; } if (preg_match($right_pattern, $email)) { echo 'Right pattern: Valid email\n'; } else { echo 'Right pattern: Invalid email\n'; } ?>
Output
Wrong pattern: Valid email
Right pattern: Invalid email
Quick Reference
Tips for email validation in PHP:
- Use
preg_matchwith a regex pattern to check format. - Escape special characters like
.and-in regex. - Consider using
filter_varfor robust validation. - Test with various email formats to avoid false positives or negatives.
Key Takeaways
Use preg_match with a regex pattern to validate email format in PHP.
Ensure your regex pattern correctly matches one @ symbol and valid characters.
Avoid overly complex regex; consider PHP's filter_var for better validation.
Test your regex with different email examples to catch edge cases.
Escape special characters in regex to prevent errors.