PHP验证字符串轻量级

I want to find the most lightweight solution to validate a string as a letter or number + ?. Eg: a? or 1? etc.

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

slighty faster than regular expression is function:

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

OK This is the fastest way

$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.0147299766541s

This solution = 1.6041090488434s

So it's 20% faster than Regexp solution :)

Some time ago, i've written a lightweight-validation class. Maybe you can use it.

For example:

$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

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

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