I want to find the most lightweight solution to validate a string as a letter or number + ?. Eg: a? or 1? etc.
-
1Are there really heavy solution to check just 2 chars?Aurelio De Rosa– Aurelio De Rosa2011-10-17 22:06:44 +00:00Commented Oct 17, 2011 at 22:06
-
You can look into regular expression. here are some examples on how it worksIbu– Ibu2011-10-17 22:07:15 +00:00Commented Oct 17, 2011 at 22:07
Add a comment
|
4 Answers
if (preg_match('/^[a-z0-9]\?$/', $str)) {
// yup, it's a letter or number + ?
}
3 Comments
Aurelio De Rosa
You can add also the i modifier to catch also the Uppercase chars.
poplitea
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.deceze
Whatever the OP means by "lightweight"... And yes, an
/i may or may not be appropriate, I'll leave that up to the OP.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
Aurelio De Rosa
Since you edit your answer, now your solution is a lot faster. Check this out: Time ord: 0.169085025787 Time regex: 0.260627031326
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/
Comments
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
deceze
Including the construction of the array? Why not make a complete static lookup table? BTW, "lightweight" doesn't necessarily mean "fastest". ;o)