单词的最小和最大规则


Minimum and Maximum rule for words?

Yii中有任何rule应该定义文本字段中的最小和最大单词数

我用了这个

array('text', 'length', 'min'=>5, 'max'=>40000),

但这是charecters,我需要最少4个字,最多4000个字,而不是character

您可以在YII侧自定义验证单词长度的规则,我正在考虑文本区域名称为描述。

public function rules()
{
    return array(
       array('description', 'validateWordLength'),
    );
}
现在您唯一需要做的就是在模型中创建一个新方法,以您刚刚声明的验证规则命名。
public function validateWordLength($attribute,$params)
{
    $total_words= str_word_count($object->$attribute);
    if($total_words>4000)
    {
       $this->addError($attribute, 'Your description length is exceeded');
    }
    if($total_words<5)
    {
       $this->addError($attribute, 'Your description length is too small');
    } 
}

尝试使用

strlen ()

函数获取字符串长度

$s = 'hello world'; //string you want to control
if(strlen($s) > 10 /*type max or min*/){
    echo 'big than 10 <br>';
}
$b = 'hello';
if(strlen($b) < 10 /*type max or min*/){
    echo 'less than 10';
}