4

I want to create a function to check if the length of a string is greater than or less than a required amount:

Something like this:

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;
 }

}

The problem is I don't know what to return. I don't want to return something like 'String is too short'. Maybe a number, 0 if == "", 1 if greater than, 2 if less than?

What would be the proper way of doing this?

4

4 に答える 4

6

多くの比較関数と同様に1、を返すことができます。この場合、戻り値には次の意味があります。0-1

  • 0: 文字列の長さが境界内にあります
  • -1: 短すぎる
  • 1: 長すぎる

これには適切な方法はないと思います。戻り値を文書化して説明するだけです。

于 2011-04-03T18:39:15.620 に答える
5

関数がブール値を返すようにします。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;
}
于 2011-04-03T18:40:51.927 に答える
0

長さが必要未満の場合は 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;
}
于 2011-04-03T18:38:14.563 に答える
0
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
}
于 2011-09-03T10:18:16.683 に答える