2012-05-16 52 views
0

這裏是我用於最少3個字符檢查的簡單代碼。 如果查詢是完全數字的(如果查詢的個案ID少於3個字符,代碼也有一個選項),我想做一個例外。搜索過濾器:最少字符數

<?php 

if (strlen($_POST['Search'])>=3) { 

include 'search.php'; 

} else { 

$message = '3+ characters, please'; 

} 

?> 

感謝您的幫助:)

回答

1

你應該寫這樣的事:

// make sure no notices are emitted if the input is not as expected 
$search = isset($_POST['Search']) ? $_POST['Search'] : null; 

if (!ctype_digit($search)) { 
    // it's all digits 
} 
else if (strlen($search) < 3) { 
    // error: less than three characters 
} 
else { 
    // default case 
} 

隨意合併分支是默認情況下,「所有數字」的情況下應轉發到相同的代碼。

重要:使用ctype_digit檢查,如果輸入的是所有數字。 is_numeric將返回true對輸入的其他類型還有:

數字字符串由可選的符號,任意數量的數字, 可選的小數部分和可選的指數部分。因此+ 0123.45e6 是一個有效的數值。十六進制符號(0xFF)也是允許的 但只有符號,小數和指數部分。

1

如果我理解正確的話:

<?php 

if (is_numeric($_POST['Search']) || strlen($_POST['Search'])>=3) { 

?> 
2

使用此:

if (strlen($_POST['Search'])>=3 ||is_numeric($_POST['Search'])) { 
    //Do stuff 
} else 
//do other stuff