1

我目前有这个代码:

if (strlen(trim($username) < 4)) {
$error='Username should be between 4 and 10 characters.';
}

if (strlen(trim($username) > 10)) {
$error='Username should be between 4 and 10 characters.';
}

我希望将其简化为一个更简单的语句,如下所示(但这显然行不通):

if (strlen(trim($username) < 4 >10))... // parse error
4

4 回答 4

3

此语法不正确,您应该使用||运算符:

if (strlen(trim($username)) < 4 || strlen(trim($username)) > 10) {
    $error='Username should be between 4 and 10 characters.';
}
于 2013-01-09T18:45:55.657 回答
3

您实际上只是在检查一个数字是否在指定范围内,所以另一个选项是filter_var(),虽然有点吓人:

if(!filter_var(strlen(trim($username)), FILTER_VALIDATE_INT, array('options' => array('min_range' => 4, 'max_range' => 10))))
{
    $error='Username should be between 4 and 10 characters.';
}
于 2013-01-09T18:52:58.707 回答
2

在这里,使用||(或)运算符会有所帮助。

另请注意我如何将用户名分配给变量,以防止多次调用您的trim()和函数。strlen()那只是浪费。

代码

$username = trim('bob');
$username_length = strlen($username);
if ($username_length < 4 || $username_length > 10)
{
    echo 'Username should be between 4 and 10 characters.';
}
于 2013-01-09T18:50:41.993 回答
-1

那么你可以这样做:

(strlen(trim($username)) < 4 || strlen(trim($username)) > 10) && $error='Username should be between 4 and 10 characters.';

但是首先定义修剪后的用户名长度会更有效:

$len = strlen(trim($usename));
($len < 4 || $len > 10) && $error = "Bad username";
于 2013-01-09T18:45:27.627 回答