我想创建一个函数来检查字符串的长度是否大于或小于所需的长度:
像这样:
function check_string_lenght($string, $min, $max)
{
if ($string == "")
{
return x;
}
elseif (strlen($string) > $max)
{
return y;
}
elseif (strlen($string) < $min)
{
return z;
}
else
{
return $string;
}
}
问题是我不知道该返回什么。我不想返回" String is too short "之类的东西。也许是一个数字,0
if == ""
, 1
大于,2
小于?
正确的做法是什么?
您可以像许多比较函数一样返回1
, 0
和-1
。在这种情况下,返回值可能具有以下含义:
-
0
:字符串长度在边界内 -
-1
: too short -
1
: too long
我认为没有合适的方法。您只需要记录并解释返回值。
我会让函数返回一个布尔值,其中TRUE
将意味着字符串在限制内,FALSE
将意味着字符串长度无效,并改变使用函数的代码部分。
此外,我将重新设计函数如下:
function is_string_length_correct( $string, $min, $max ) {
$l = mb_strlen($string);
return ($l >= $min && $l <= $max);
}
使用该函数的那部分代码可能如下所示:
if (!is_string_length_correct($string, $min, $max)) {
echo "Your string must be at least $min characters long at at
most $max characters long";
return;
}
如果长度小于要求则返回0如果大于要求则返回-1如果在范围内则返回1
function check_string_lenght($string, $min, $max)
{
if (strlen($string)<$min)
return 0;
elseif (strlen($string) > $max)
return -1;
else
return 1;
}
function checkWord_len($string, $nr_limit) {
$text_words = explode(" ", $string);
$text_count = count($text_words);
for ($i=0; $i < $text_count; $i++){ //Get the array words from text
// echo $text_words[$i] ; "
//Get the array words from text
$cc = (strlen($text_words[$i])) ;//Get the lenght char of each words from array
if($cc > $nr_limit) //Check the limit
{
$d = "0" ;
}
}
return $d ; //Return the value or null
}
$string_to_check = " heare is your text to check"; //Text to check
$nr_string_limit = '5' ; //Value of limit len word
$rez_fin = checkWord_len($string_to_check,$nr_string_limit) ;
if($rez_fin =='0')
{
echo "false";
//Execute the false code
}
elseif($rez_fin == null)
{
echo "true";
//Execute the true code
}