0

It's usually recommended to use filter_var function for validating email addresses in PHP – however, the option of using regex is sometimes selected by the developers. For instance, Codeigniter's email helper is relying on a regular expression for validating email addresses.

What could be the advantage of selecting the regex approach rather than relying on filter_var?

Thank you in advance!

NOTE: This is not a practical question about "how to validate emails in PHP", but a theoretical question regarding PHP best practices. Please read carefully to understand the nature of the question, before marking it as a duplicate of something it does NOT duplicate. Thank you!

Dimitri Vorontzov
  • 7,834
  • 12
  • 48
  • 76
  • 2
    Surely answers like http://stackoverflow.com/questions/5855811/how-to-validate-an-email-in-php cover this already? – mikebabcock Feb 23 '13 at 04:44
  • 1
    It could be a legacy code that has yet to be updated from early version of CI. `filter_var()` was not available until `5.2.0` which in versioning terms was not that long ago. – kittycat Feb 23 '13 at 04:46
  • @mikebabcock – uh... not quite: there's nothing in that answer that would directly address the issue I am enquiring about. Still, thank you very much for supplying that link, it is a very valuable bit of information. – Dimitri Vorontzov Feb 23 '13 at 04:54
  • @cryptic ツ – thank you, this may indeed be the reason they used it. – Dimitri Vorontzov Feb 23 '13 at 04:55

1 Answers1

1

FILTER_VALIDATE_EMAIL will validate the email address according to standards. like if you will validate

'0test\'mail_check@testing.com'

with filter_var you will get output as true. But in actual this is not a valid email and you can track this using regular expressions.

Regular expressions gives you much control, but at the same time regular expressions are complicated and filter_var is cleaner.

So it's you who can decide what to use . :)

  • Good answer, although it could be improved by showing an example RegEx that solves the problem you identified. – Aaron Brager Feb 23 '13 at 05:14
  • @AaronBrager - good idea, but I'm not sure Abhishek is still online to expand on his answer. May I ask you please to show such example, if you could? – Dimitri Vorontzov Feb 23 '13 at 05:19
  • 1
    you can use codeigniter email validation `code`function valid_email($str) { return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE; } – Abhishek Kumar Srivastava Feb 23 '13 at 06:06