我想检查输入字段是否为空,以及他是否具有特殊字符。我尝试过:
function stringValidator($field) {
if(!empty($field) && (!filter_var($field, FILTER_SANITIZE_STRING)))
{
return "You typed $field: please don't use special characters
'<' '>' '_' '/' etc.";
} }
PHP甚至没有尝试通过这种方式进行验证。 有提示吗?
答案 0 :(得分:0)
一个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";
}
通话会很好地工作。
代码:(Demo)
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";
}
通话:
代码:(Demo)
hello: valid
what_the: You typed what_the: please use only alphanumeric characters
输出:
String