我目前有这段代码:
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
答案 0 :(得分:4)
此语法不正确,您应使用||
运算符:
if (strlen(trim($username)) < 4 || strlen(trim($username)) > 10) {
$error='Username should be between 4 and 10 characters.';
}
答案 1 :(得分: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.';
}
答案 2 :(得分: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.';
}
答案 3 :(得分:0)
你可以做到:
(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";