字符串长度验证 php 形式

String Length validation php form

这是我的代码,用于检查该字段是否为空并且工作正常,但是我想检查两者,是否为空以及是否少于 10 个字符

<pre>
        if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
</pre>

我试过了

<pre>
        if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
        if(strlen($_POST['comments']) > 10){ $errors[]="Please enter a comment."; }
</pre>

然而,这并没有奏效,所以我尝试了两者都没有奏效的相同结果

<pre>
        if(empty($_POST['comments']) && strlen($_POST['comments']) > 10)){ $errors[]="Your 
         comment must be longer than 10 characters."; }
</pre>

我也试过 mb_strlen,但没有任何改变。

你的逻辑有点不对。如果字符串为空 且长度 超过 10 个字符(这将是一个悖论),您当前正在添加错误。

您需要检查字符串是否为空 或更少 然后 10 个字符。

试试这个:

if (empty($_POST['comments']) || strlen($_POST['comments']) < 10) {
    $errors[] = "Your comment must be longer than 10 characters.";
}

该条件检查字符串是否为空 字符串是否少于 < 10 个字符。

&&表示
||表示
<表示小于
>表示大于

您可以在手册中阅读有关 logical and comparison operators 的更多信息。