user1709910
user1709910

Reputation: 31

PHP: Check does email contains "@" and "."

Im new in php and this should be a easy to make, but I dont now how. I want to check does $address has characters "@" and "."

<?php 
    function testEmail($address){
        $a = strpos("/@/", $address);
        $b = strpos("/./", $address);
        if (($a != false) && ($b != false)) {
            echo "Email is OK";
        } else {
            echo "Email is NOT OK";
        }
    }
    testEmail("[email protected]");
?>

Upvotes: 2

Views: 4186

Answers (3)

wroniasty
wroniasty

Reputation: 8052

<?php
function testEmail($address) {
    if (preg_match ( "/\.|@/", $address)) 
       echo "Email OK";
    else
       echo "Email not OK";
}
?>

a better way to check for valid email address:

<?
function isValidEmail($email){
return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email);
}
?>

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151586

Is your question about this specific piece of code? Then @wroniasty's answer is correct. But you really don't want to use a regex to test email validity, unless you want to use monstrosities like these.

However, if your question really is "How can I validate an email address?", then take a look at filter_var().

You can pass it the filter FILTER_VALIDATE_EMAIL, so it will validate the email address catching quite a bit of edge cases.

You can check an address using the following code:

if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
    // valid email
} else {
    // invalid email
}

Upvotes: 2

GBD
GBD

Reputation: 15981

You can simply use filter_var to check validity of email.

$email = '[email protected]'
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Email correct
}
else {
//Email not correct
}

Upvotes: 9

Related Questions