0

I'm not very knowledgeable with regular expresions, so I don't understand why I'm getting this error.

I'm using the following code to match all the emails in the string $str and saving them in the array $match:

preg_match_all(
    "/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/",
    $str,
    $match
);

Apparently there's a problem in the regex (which I got from here) because I'm getting this error:

Warning: preg_match_all() [function.preg-match-all]: Unknown modifier '=' in C:\xampp\htdocs\project\Framework\Sanitizer.class.php on line 38

Can someone tell me what's the problem?

Thanks

federico-t
  • 12,014
  • 19
  • 67
  • 111

2 Answers2

4

You have to escape the forward slash before that equals sign, e.g:

preg_match_all(
    "/^[a-zA-Z0-9.!#$%&’*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/",
    $str,
    $match
);

"/" is the delimiter for the whole expression, so it must be escaped in the regex itself

orourkek
  • 2,091
  • 15
  • 22
1

You need to escape many of the characters in that string with a backslash. Some of those you want to escape is: /?^{|} .

I would have written it like this:

preg_match_all(
    "/^[a-zA-Z0-9.!#$%&’*+\/=\?\^_`\{\|\}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/",
    $str,
    $match
);

I find this site quite useful when it comes to matching e-mail adresses:

http://www.regular-expressions.info/email.html

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
  • Might want to point exactly WHICH usages of those chars need to be escaped. There's a few places where they're a valid unescaped usage. – Marc B Apr 05 '12 at 19:48
  • I'm no expert in regular expressions, but I find this a useful site when it comes to regexps for e-mail matching: http://www.regular-expressions.info/email.html . – Simon Forsberg Apr 05 '12 at 22:27