How to change PHP’s eregi to preg_match [duplicate]

Perl-style regex patterns always need to be delimited. The very first character in the string is considered the delimiter, so something like this:

function validate_email($email) {
    if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", $email)) {
        echo 'bad email';
    } else {
        echo 'good email';
    }
}

The reason your initial attempt didn’t work is because it was trying to use ^ as the delimiter character but (obviously) found no matching ^ for the end of the regex.

Leave a Comment