字符串最小、最大长度函数
我正在尝试检查字符串的最小和最大长度:
如果我向其传递一个数组,如下所示,我希望如果 true 则返回值,如果 false 则返回 NULL:
$lenghts = array('a' => array('min' => 20, 'max' => 70),
'b' => array('min' => 50, 'max' => 800),
'c' => array('min' => 3, 'max' =>8));
值是:
$values = array('thread_title' => 'this is it', 'thread_content' => 'this is not it', 'thread_tags' => 'also not it')
;
编辑
现在就像凌晨 5 点(真的很困),我应该复制并粘贴正确的版本,抱歉:
function string_min_max($string_array, $array)
{
$returns = array(); # store returned values
foreach ($array as $key)
{
# check for minimum:
if (array_key_exists('min', $key))
{
$minimum = (strlen($string_array[$key]) < $key['min'] ? $key = NULL : $key);
}
if (array_key_exists('max', $key))
{
$maximum = (strlen($string_array($key)) > $key['max'] ? $key = NULL : $key);
}
if ($minimum !== NULL && $maximum !== NULL)
{
$returns[$key]['min'] = $minimum;
$returns[$key]['max'] = $maximum;
}
}
}
这不起作用:
string_min_max($values, $lengths);
I'm trying to check min and max length of strings:
If I pass it an array, such as follows, I want the values to be returned if true and NULL if false:
$lenghts = array('a' => array('min' => 20, 'max' => 70),
'b' => array('min' => 50, 'max' => 800),
'c' => array('min' => 3, 'max' =>8));
And the values are:
$values = array('thread_title' => 'this is it', 'thread_content' => 'this is not it', 'thread_tags' => 'also not it')
;
EDIT
It's like 5am here (really quite sleepy), I should copied and pasted the correct version, sorry:
function string_min_max($string_array, $array)
{
$returns = array(); # store returned values
foreach ($array as $key)
{
# check for minimum:
if (array_key_exists('min', $key))
{
$minimum = (strlen($string_array[$key]) < $key['min'] ? $key = NULL : $key);
}
if (array_key_exists('max', $key))
{
$maximum = (strlen($string_array($key)) > $key['max'] ? $key = NULL : $key);
}
if ($minimum !== NULL && $maximum !== NULL)
{
$returns[$key]['min'] = $minimum;
$returns[$key]['max'] = $maximum;
}
}
}
This does not work:
string_min_max($values, $lengths);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这段代码可以简化为:
OR:
OR:
OR:
所以答案是:不。这是行不通的。
This code is reducable to:
OR:
OR:
OR:
So the answer is: no. It won't work.
如果不过多关注细节,一个明显的问题是您没有从函数中返回任何内容;您正在构建一个数组,但您不使用它,因此它会在函数结束时被销毁。
我认为至少你在函数结束时需要这个:
然后你可以像这样调用你的函数:
Without looking too much at the details, one obvious problem is that you are not returning anyting from your function; you are building an array but you don´t use it so it gets destroyed at the moment your function ends.
I think that at least you will need this at the end of your function:
You can then call your function like:
如果使用它来按长度和字符验证字符串:
if use this for validate string by length and chars :