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

时间:2018-11-04 23:21:19

标签: 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 
            '<' '>' '_' '/' etc.";

    } }

PHP甚至没有尝试通过这种方式进行验证。 有提示吗?

1 个答案:

答案 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