Quick Tip: Validate Email Addresses with PHP: "
Email validation is a common task that most developers have to deal with on a regular basis. Far too often the complex approach is taken (regular expressions), when PHP 5 has a super simple way to validate / sanitize your email string.
Filtering Variables the PHP 5 Way
So what is the quick method to validating emails? The function called filter_var(). This function allows you to run your variable through a filter that you specify, and can either validate the variable, or return a sanitized string depending on the filter you choose.
What does this look like…
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Alternatively you can use the sanitize filter, and it will remove any characters that aren’t valid.
1 2 3 4 5 6 7 8 9 | <?php //Crappy email. $var="bad%%@em\#ail.com"; //Runs email through a sanitize filter print filter_var($var, FILTER_SANITIZE_EMAIL); //Result - bad@email.com ?> |
As you can see these are super easy. You no longer have to worry about your regular expressions sucking. Php has you covered."