Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP检查输入字段是否为空以及是否有特殊字符_Php_String_Validation_Special Characters - Fatal编程技术网

PHP检查输入字段是否为空以及是否有特殊字符

PHP检查输入字段是否为空以及是否有特殊字符,php,string,validation,special-characters,Php,String,Validation,Special Characters,我想检查输入字段是否为空,是否有特殊字符。我试过这个: function stringValidator($field) { if(!empty($field) && (!filter_var($field, FILTER_SANITIZE_STRING))) { return "You typed $field: please don't use special characters '<' '&

我想检查输入字段是否为空,是否有特殊字符。我试过这个:

function stringValidator($field) {   

    if(!empty($field) && (!filter_var($field, FILTER_SANITIZE_STRING)))
    {

            return "You typed $field: please don't use special characters 
            '<' '>' '_' '/' etc.";

    } }
函数stringValidator($field){
如果(!empty($field)&(!filter_var($field,filter_SANITIZE_STRING)))
{
return“您键入的$field:请不要使用特殊字符
“等”;
} }
PHP甚至没有尝试以这种方式进行验证。 有什么建议吗?

A
preg\u match()
调用会很好地工作

代码:()

输出:

hello: valid
what_the: You typed what_the: please don't use special characters 
            '<' '>' '_' '/' etc.
hello: valid
what_the: You typed what_the: please use only alphanumeric characters

(公平地说,这是一个糟糕的记录。)@Philipedsouzasantos我解决了你的问题了吗?有什么反馈吗?
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