2009-10-24 132 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