Skip to content
PHP Logo

What is the issue with using preg_match() in PHP and how can it be resolved?

The issue with using preg_match() in PHP is that it can return false if an error occurs, making it difficult to troubleshoot. To resolve this, you can use preg_last_error() to check for errors after calling preg_match().

php
$pattern = '/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/';
$email = 'example@email.com';

if (preg_match($pattern, $email)) {
    echo 'Email is valid.';
} else {
    if (preg_last_error() !== PREG_NO_ERROR) {
        echo 'Error in regex pattern.';
    } else {
        echo 'Email is not valid.';
    }
}