How to change PHP's eregi to preg_match [duplicate]
Asked Answered
K

2

20

Possible Duplicate:
How can I convert ereg expressions to preg in PHP?

I need help, below is a small VERY basic regex to somewhat validate an email, I do realize it does not work the greatest but for my needs it is ok for now.

It currently uses PHP's eregi function which php.net says is now a depreciated function and I should use preg_match instead, simply replacing erei with preg_match does not work, can someone show me how to make it work?

function validate_email($email) {
    if (!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {
        echo 'bad email';
    } else {
        echo 'good email';
    }
}
function validate_email($email) {
    if (!preg_match("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {
        echo 'bad email';
    } else {
        echo 'good email';
    }
}
Kirksey answered 3/9, 2009 at 17:42 Comment(3)
Note that you should not use this regex to validate e-mail; it is severely outdated.Idiolect
@Piskvor I agree, this question is nearly 5 years old too =) you should post an updated answer if you like and I can always change the "selected" answer to the best approachKirksey
It's IMHO outside of the scope of the ereg/preg issue; commenting seems sufficient to me.Idiolect
M
32

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.

Montagnard answered 3/9, 2009 at 17:45 Comment(2)
Thanks, I just found php's FILTER_VALIDATE_EMAIL, it seems like it might be the best way to go but I cannot find much information on itKirksey
@jasondavis, FILTER_VALIDATE_EMAIL would definitely be a better choice. E-mails are complicated.Rolanderolando
B
10

You will need to change three things

  1. need to add pattern delimiters (can be any character, but most commonly a forward slash)
  2. [[:alnum:]] will need to be replaced with the PCRE equivalent
  3. The "i" in "eregi" means case-insensitive, which PCRE does with a flag, specifically the i flag.

Otherwise, the rest looks PCRE compatible (yes, that's kind of redundant =P)

"/^[a-z0-9][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i"
Bewitch answered 3/9, 2009 at 17:49 Comment(1)
PHP's PCRE includes things like [:alnum:] as options.Montagnard

© 2022 - 2024 — McMap. All rights reserved.