2011-04-03 40 views
4

我想創建一個函數來檢查,如果字符串的長度比所需的金額大於或小於:功能檢查,如果字符串長度大於或小於所需量

事情是這樣的:

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太短'的內容。也許一個號碼,0if == "",1如果大於,2如果小於?

這樣做的正確方法是什麼?

回答

6

可以返回10-1像很多比較函數做需要則返回0低。在這種情況下,返回值可以有以下含義:

  • 0:字符串長度的範圍內
  • -1:太短
  • 1:太長

我不認爲這是一個合適的方式。你只需要記錄和解釋返回值。

+0

什麼空? – 2011-04-03 18:42:44

+3

@johnathanross:你是什麼意思?空字符串的長度爲'0'時太短。 – 2011-04-03 18:43:31

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

我將有函數返回一個布爾值,其中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

好東西XD! – Jake 2013-04-02 16:17:33

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 
}