2011-10-17 45 views
0

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

+1

真的有重液检查仅2个字符? –

+0

你可以看看正则表达式。这里有一些关于[如何工作]的例子(http://php.net/manual/en/function.preg-match.php) – Ibu

+0

is_string()....? – sdolgy

回答

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

你也可以添加我修改器来捕捉大写字母。 –

+0

Regex可能不是这里最轻量级的解决方案吗?无论如何,在模式的末尾添加一个'i'使其不区分大小写。 – poplitea

+0

无论OP的意思是“轻量级”......是的,“/ i”可能适用也可能不适用,我会把它留给OP。 – deceze

1

略低快于正则表达式的功能:

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

我觉得'chr('a')'不太正确。 – deceze

+0

@deceze当然它的'ord()'固定的 – Peter

+0

由于你编辑你的答案,现在你的解决方案要快得多。检查:时间ord:0.169085025787 时间正则表达式:0.260627031326 –

-1

确定这是最快的方式

$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]); 
} 

正则表达式= 2.0147299766541 s

该解决方案= 1.6041090488434s

所以它比正则表达式的解决方案:)

+1

包括数组的构造?为什么不制作一个完整的静态查找表?顺便说一下,“轻量级”并不一定意味着“最快”。 ; O) – deceze

0

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

例如:

$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