0

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

2
  • 1
    Are there really heavy solution to check just 2 chars? Commented Oct 17, 2011 at 22:06
  • You can look into regular expression. here are some examples on how it works Commented Oct 17, 2011 at 22:07

4 Answers 4

4
if (preg_match('/^[a-z0-9]\?$/', $str)) {
    // yup, it's a letter or number + ?
}
Sign up to request clarification or add additional context in comments.

3 Comments

You can add also the i modifier to catch also the Uppercase chars.
Regex is probably not the most lightweight solution here? In any case, add an i in the end of the pattern to make it case-insensitive.
Whatever the OP means by "lightweight"... And yes, an /i may or may not be appropriate, I'll leave that up to the OP.
1

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] == '?'
        )
    );
}

1 Comment

Since you edit your answer, now your solution is a lot faster. Check this out: Time ord: 0.169085025787 Time regex: 0.260627031326
0

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

Comments

-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 :)

1 Comment

Including the construction of the array? Why not make a complete static lookup table? BTW, "lightweight" doesn't necessarily mean "fastest". ;o)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.