E-mail format REGEX PHP- there are many like it but this one is mine
-
18-09-2019 - |
Question
Uh, and it's broken:
I had a perfectly working regex that allowed all the numbers, letters and only e-mail relevant punctuation (._-@) to sanitize my email fields, and then I thought it would be nice adding a proper email regex, checking for the correct pattern. This is what I have now:
function check_chars_email($str) {
$str_replace = preg_replace("/[^a-zA-Z0-9-@_\.]/","",$str);
if(preg_match("/^(.*)@(.*)\.(.*)$/", $str_replace)) {
return $str_replace;
} else {
return FALSE;
}
I'm aware I don't need the brackets around the .* but find it makes it more legible.
When I call that function, it is like this:
$esc_email = mysqli_real_escape_string($mysqli, check_chars_email($_POST["email"]));
$tr_email = trim($esc_email);
$_SESSION["email"] = $tr_email;
And I then use, among other things, this to verify it at the start of my registration script:
($tr_email === FALSE)
And despite trying it with a valid e-mail address, I get a failure. I am also testing if the variable is empty, so I guess I could try ==FALSE instead of ===, but I want to be as precise as possible.
Anyone have any thoughts?
Solution
Why would you use a regex for this when PHP already does it?
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// it's valid
}
See filter_var()
and validate filters.