How to validate an email address in PHP ?

PHPProgrammingServer Side Programming

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

 Live Demo

<?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("alex@tutorialspoint.com")){
      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

 Live Demo

<?php
   $email = "pattrick@tutorialspoint.com";
   // 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

pattrick@tutorialspoint.com is a valid email address
raja
Published on 26-Jun-2019 16:49:22
Advertisements