2011-10-17 53 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