I would like to check if a string contains only these characters :
A-Z
a-z
0-9
-
@
_
.
The purpose is to check if a mail is valid in a form.
I am doing this :
if(preg_match('/[a-z0-9\._\-\@]/i', $email) === 0) {
echo 'not valid';
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'not valid';
}
but is doesn't return an error if there is a special character like
test%@test.fr
preg_match('/[a-z0-9._-\\@]/i', $email)
This will return true if any valid characters are found but you want to match any non-valid characters - so invert the character class:
preg_match('/[^a-z0-9\._\-\@]/i', $email)
Alternatively you could require that it only contains the valid characters:
if (!(preg_match('/^([a-z0-9\._\-\@]+)$/', $email)) {
BTW as an email address (more specifically an ADDR_SPEC validator) this sucks big time - it will pass non-valid email addresses and fail valid ones.
Who told you that '%' is invalid in a mailbox name?
Currently I use this:
/^[a-z0-9\._%+!$&*=^|~#%'`?{}/\-]+@([a-z0-9\-]+\.){1,}([a-z]{2,20})$/gi
(which still excludes some valid ADDR_SPECs - but for specific reasons - and has some issues with idn)
...but would suggest you just use filter_var() and ditch the regex.
The regex /[a-z0-9\\._\\-\\@]/i
checks only of some of the listed characters are in the $email
. It does not disallow any other characters in the $email
.
In order to restrict the input to the listed characters only define a sequence of them ( [a-z0-9\\._\\-\\@]+
, notice the +
quantifier) and require it to be the only sequence in the input by surrounding with ^
and $
(start of string and end of string anchors respectively):
if(preg_match('/^[a-z0-9\._\-\@]+$/i', $email) === 0) {
echo 'not valid';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.