如果输入的文本超过2个字符且不超过15个字符,请通知用户

时间:2017-01-14 14:09:30

标签: php

我正在尝试使用此代码通知用户他们输入到输入字段的文本是否超过2个字符且少于15个字符:

<?php
if(isset($_POST['submit'])) {
   $text = $_POST['text'];
   if(!empty($text)) {
      if(!strlen($text) < 2 && (!strlen($text) > 15)) {
         echo 'More than 2 characters and no more than 15 characters';
      }
   }
}
?>

<form method="post">
    <input type="text" name="text" maxlength="15" pattern=".{2,15}" required title="Please enter a username with at least 2 characters and no more than 15." required>
    <input type="submit" name="submit">
</form>

问题是,当if语句正确时,不会显示echo语句。

2 个答案:

答案 0 :(得分:1)

这是一个合适的条件:

if (strlen($text) > 2 && strlen($text) < 15) {
    echo 'More than 2 characters and no more than 15 characters';
}

答案 1 :(得分:0)

根据operator precedence!优先于>,所以这个:

!strlen($text) > 15

...等于:

(!strlen($text)) > 15 // Parenthesis added to make precedence obvious

我还建议您切换到mb_strlen()以使其具有多字节感知能力。

相关问题