PHP验证字符串轻量级


PHP validate string lightweight

我想找到最轻量级的解决方案来验证字符串为a letter or number + ?。例如:a?1?

if (preg_match('/^[a-z0-9]'?$/', $str)) {
    // yup, it's a letter or number + ?
}

比正则表达式略快:

// return true or false
function validate($str) {
    $str0 = ord($str[0]);
    return(
        (
            ($str0 >= 97 && $str0 <= 122) or
            ($str0 >= 48 && $str0 <= 57)
        ) &&
        (
            $str[1] == '?'
        )
    );
}

前段时间,我写了一个轻量级验证类。也许你可以用它。

例如:

$oValidator = new Validator();
$oValidator->isValid('a', 'alpha_numeric|max_length[1]'); //true
$oValidator->isValid('1', 'alpha_numeric|max_length[1]'); //true
$oValidator->isValid('ab', 'alpha_numeric|max_length[1]'); //false
$oValidator->isValid('1337', 'alpha_numeric|max_length[1]'); //false

例子:http://sklueh.de/2012/09/lightweight-validator-in-php/

github: https://github.com/sklueh/Lightweight-PHP-Validator

OK这是最快的方法

$allowed_char = Array();
for($i=ord('a');$i<=ord('z');$i++) $allowed_char[chr($i)] = true;
for($i=ord('0');$i<=ord('9');$i++) $allowed_char[chr($i)] = true;
function validate($str) {
    global $allowed_char;
    return $allowed_char[$str[0]] && $str[1] == '?' && !isset($str[2]);
}

Regexp = 2.014729976651s

此解决方案= 1.6041090488434s

所以它比Regexp解决方案快20%:)