Validate email address in php

Here are a few ways to validate an email address in PHP:

Method 1: Using a Regular Expression

function validateEmail($email) {
    $regex = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
    if (preg_match($regex, $email)) {
        return true;
    } else {
        return false;
    }
}

This regular expression checks for the following:

Method 2: Using PHP's built-in filter_var function

function validateEmail($email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

The filter_var function uses a built-in email validation filter to check if the email address is valid.

Method 3: Using a combination of string functions

function validateEmail($email) {
    $parts = explode('@', $email);
    if (count($parts)!= 2) {
        return false;
    }
    $localPart = $parts[0];
    $domain = $parts[1];
    if (!preg_match('/^[a-zA-Z0-9._%+-]+$/', $localPart) ||!preg_match('/^[a-zA-Z0-9.-]+$/', $domain)) {
        return false;
    }
    $tld = explode('.', $domain);
    if (count($tld) < 2) {
        return false;
    }
    return true;
}

This function checks for the following:

You can use any of these methods to validate an email address in PHP. Note that email validation is not foolproof, and it's possible for a user to enter an invalid email address that still passes validation.