A preg_match()
вызов будет работать хорошо.
Код: ( Демо )
function stringValidator($field) {
if(!empty($field) && preg_match('~[^a-z\d]~i', $field)) {
return "You typed $field: please don't use special characters '<' '>' '_' '/' etc.";
}
return "valid"; // empty or valid
}
$strings = ["hello", "what_the"];
foreach ($strings as $string) {
echo "$string: " , stringValidator($string) , "\n";
}
Выход:
hello: valid
what_the: You typed what_the: please don't use special characters
'<' '>' '_' '/' etc.
Или ctype_
вызов:
Код: ( Демо )
function stringValidator($field) {
if(!empty($field) && !ctype_alnum($field)) {
return "You typed $field: please use only alphanumeric characters";
}
return "valid"; // empty or valid
}
$strings = ["hello", "what_the"];
foreach ($strings as $string) {
echo "$string: " , stringValidator($string) , "\n";
}
Выход:
hello: valid
what_the: You typed what_the: please use only alphanumeric characters