Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php regex string needs more delimiters?

Tags:

regex

php

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?

like image 860
xbonez Avatar asked Jul 11 '26 09:07

xbonez


2 Answers

You escape your delimiters, f.e:

$sCorrect = "/[a-z]/";
$sFalse = "\/[a-z]\/";

Even better, use:

filter_var($sVariable, FILTER_VALIDATE_EMAIL);
like image 129
Wesley van Opdorp Avatar answered Jul 13 '26 08:07

Wesley van Opdorp


You escaped too many characters:

$reg = "/^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/";
  • The / regex delimiters (at the start and end of your regex) shouldn't be escaped
  • The metacharacters ^ and $ shouldn't be escaped.
  • The dot needs not to be escaped (but can be) when it's in a character class
  • The @ 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

like image 26
NullUserException Avatar answered Jul 13 '26 10:07

NullUserException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!