I'm trying to use regex to check the validity of an email address in a php script. I use the following string as my regex
$reg = "\/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})\$\/";
I keep getting an error:
Warning: preg_match(): Delimiter must not be alphanumeric or backslash
I've done my best to escape all special characters. is there something I'm missing?
You escape your delimiters, f.e:
$sCorrect = "/[a-z]/";
$sFalse = "\/[a-z]\/";
Even better, use:
filter_var($sVariable, FILTER_VALIDATE_EMAIL);
You escaped too many characters:
$reg = "/^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/";
/ regex delimiters (at the start and end of your regex) shouldn't be escaped^ and $ shouldn't be escaped.@ needs not to be escaped (but can be)Regardless, creating your own regex to validate email addresses can be tricky. Most likely you are disallowing valid emails (eg: + is a valid character you are not allowing) and/or allowing invalid ones. The standards for this are set by RFC 822, I believe - and they are loooooooong.
Just use filter_var() as suggested by Wesley. Or better yet, send an email to the supplied address. That's the best and most reliable way to determine if the address is
a) valid
b) belongs to the user
An interesting read: I Knew How To Validate An Email Address Until I Read The RFC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With