- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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("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
<?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
Advertisements