Computer >> Computer tutorials >  >> Programming >> PHP

How to validate an email address in PHP ?


In this article, we will learn to validate an email with PHP regular expression. We will learn different methods to validate email address in PHP.

Method1

The function preg_match() checks the input matching with patterns using regular expressions.

Example

<?php
   function checkemail($str) {
         return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
   }
   if(!checkemail("[email protected]")){
      echo "Invalid email address.";
   }
   else{
      echo "Valid email address.";
   }
?>

Output

Valid email address.

In the above example PHP preg_match() function has been used to search string for a pattern and PHP ternary operator has been used to return the true or false value based on the preg_match return.

Method 2

We will discuss email validation using filter_var() method.

Example

<?php
   $email = "[email protected]";
   // Validate email
   if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo("$email is a valid email address");
   }
   else{
      echo("$email is not a valid email address");
   }
?>

Output

[email protected] is a valid email address