2009-10-24 76 views
2

我一直在尋找一種方法來創建一個函數來檢查一個字符串是否包含除小寫字母和數字之外的任何內容,以及它是否返回false。我在互聯網上搜索,但我能找到的是舊方法,需要您使用現在在PHP5中棄用的函數。只允許字符串中的某些字符

回答

2
function check_input($text) { 
    if(preg_match("/[^a-z0-9]/", $text)) { 
    return false; 
    } 
    else { 
    return true; 
    } 
} 
0

要mixen了一點東西

<? 
$input = "hello world 123!"; 
$digits = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); 

if (ctype_alnum($input)) 
{ 
    if (ctype_lower(str_replace($digits, "", $input))) 
    { 
     // Input is only lowercase and digits 
    } 
} 
?> 

但正則表達式可能是去這裏的路! =)

1

使用正則表達式。使用preg_match()

$matches = preg_match('/[^a-z0-9]/', $string); 

所以,現在如果$matches1,你知道$string包含錯誤的字符。否則$matches0,並且$string是確定的。

+1

請記住,這個功能可以返回爲假,所以你應該看看使用的類型比較運算,''===: $匹配=的preg_match('/ [^ A-Z0-9] /',$ string); if($ matches === 0){ //代碼在這裏匹配時 } – 2009-10-24 01:09:10