Complex Regex Help

I have this regex below, but it keeps throwing a warning and invalids all email address.

Warning: preg_match(): Unknown modifier ‘_’ in C:\www\preg_match.php on line 17
Invalid email

Code:


$string = "example@domain.co.uk";

if (preg_match("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$", $string)) {

echo 'Valid email'; } else {

echo 'Invalid email'; }

Hi,

Writing regex patterns is a bit of a black art. A simpler alternative to valid email addresses in PHP is to use [fphp]filter_var[/fphp]:

filter_var('example@domain.co.uk', FILTER_VALIDATE_EMAIL);

This will return the email address if valid, or FALSE if not.

thanks, I really need someone spot what the issue with that particular regex is, I know there exists alternatives, but i need to use the above.

can anyone crack it??

You forgot your delimiters. PHP thinks your delimiter is ^, because thats the first character in the string. Find the second instance of ^ in the pattern, and you’ll see that the following character is a _.

I would suggest using ~ as a delimiter, and sticking \ in before any ~'s in the current string. (From what i can see, the pattern uses all Shift-Num characters in it.)

perfect this worked. thanks StarLion

You also might want to specify an “i” modifier (Case-Insensitive) after your closing delimiter - the pattern you have described looks for lower case letters only.