只允许字符串中的某些字符

时间:2009-10-24 00:59:28

标签: php string function filter

我一直在寻找一种方法来创建一个函数,以检查字符串是否包含除小写字母和数字之外的任何内容,以及它是否返回false。我在互联网上搜索过但我能找到的只是旧方法,要求你使用PHP5中现已弃用的函数。

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

使用正则表达式。使用preg_match()

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

现在如果$matches1,您知道$string包含错误字符。否则$matches0$string即可。

答案 2 :(得分:0)

稍微混淆一下

<?
$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
    }
}
?>

但正则表达式可能就是去这里的方式! =)

相关问题