检查字符串长度、最大值和最小值
有没有一个函数可以检查字符串是否太长或太短,我通常会在几个地方写这样的东西:
if (strlen($input) < 12)
{
echo "Input is too short, minimum is 12 characters (20 max).";
}
elseif(strlen($input) > 20)
{
echo "Input is too long, maximum is 20 characters.";
}
我知道你可以轻松编写一个函数,但是 PHP 中有内置函数吗?
我通常在验证输入时收集错误,因此上面的代码将被编写:
$errors = array();
if (strlen($input) < 12)
{
$errors['field_name'] = "Field Name is too short, minimum is 12 characters (20 max).";
}
elseif(strlen($input) > 20)
{
$errors['field_name'] = "Field Name is too long, maximum is 20 characters.";
}
如何将其制作成函数^?
Is there a function to check if a string is too long or too short, I normally end up writing something like this in several places:
if (strlen($input) < 12)
{
echo "Input is too short, minimum is 12 characters (20 max).";
}
elseif(strlen($input) > 20)
{
echo "Input is too long, maximum is 20 characters.";
}
I know you can easily write one but is there one built into PHP?
I normally collect errors as I validate input, so the above code would be written:
$errors = array();
if (strlen($input) < 12)
{
$errors['field_name'] = "Field Name is too short, minimum is 12 characters (20 max).";
}
elseif(strlen($input) > 20)
{
$errors['field_name'] = "Field Name is too long, maximum is 20 characters.";
}
How can that be made into a function ^?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我想你可以做一个这样的函数:
然后你可以做这样的事情:
I guess you can make a function like this:
Then you can do something like this:
PHP 验证最小和最大整数,您可以使用以下命令:
PHP validate minimum and maximum integer number you can use this:
怎么样:
只需根据需要多次调用 addError('error message here') ,然后在最后调用 printErrors() 即可。
How about something like:
Just call addError('error message here') as many times as you need, followed by a printErrors() call at the end.
您可以创建一个利用 会话变量 的错误函数:
此处演示:<强>http://codepad.org/TKigVlCj
you can make a error function that utilizes session vars:
Demo here: http://codepad.org/TKigVlCj
这个怎么样:
How about this: