This question already has an answer here:
I am trying to match a regular expression in PHP, using the following code.
if (!preg_match("/^[a-zA-Z0-9-_.]*$/",$string)) {
// Show error
}
I want to allow
It does not work. Does anyone have any suggestions for what I am doing wrong?
</div>
You should use:
if (!preg_match("/^[\w\s\.-]*$/",$string)) {
#show error
}
It will also match empty string because of '*'.
You're practically there.
if (preg_match('/^[a-zA-Z0-9-_. ]*$/', $string) !== 1) {
// Show error
}
Assuming you want to allow empty strings. Otherwise, change *
to +
.