fork(1) download
  1. <?php
  2.  
  3. $str = "23456789ABCDEGHJKMNPQRSTUVXYZabcdeghjkmnpqrstuvxyz";
  4. $excludes = ['cp','cb','ck','c6','c9','rn','rm','mm','co','do','cl','db','qp','qb','dp','ww'];
  5. $length = 5;
  6.  
  7. $indexedExcludes = array_combine($excludes, $excludes);
  8. $dictionaryArray = str_split($str);
  9.  
  10. function fastCaptcha(array $dictionary, array $excludedSyllables, int $length): string
  11. {
  12. $captcha = '';
  13. $previousCharacter = '';
  14. $generatedLength = 0;
  15.  
  16. while ($generatedLength < $length) {
  17. $randomCharacter = $dictionary[array_rand($dictionary)];
  18.  
  19. if(array_key_exists($previousCharacter . $randomCharacter, $excludedSyllables)) {
  20. continue;
  21. }
  22.  
  23. $captcha .= $randomCharacter;
  24. $previousCharacter = $randomCharacter;
  25. $generatedLength++;
  26. }
  27.  
  28. return $captcha;
  29. }
  30.  
  31. $excludesRegex = '/' . implode('|', $excludes) . '/';
  32.  
  33. function fuckedCaptcha(string $dictionary, string $excludedSyllables, int $length): string
  34. {
  35. do {
  36. $code = substr(str_shuffle(str_repeat($dictionary, 3)), 0, $length);
  37. } while (preg_match($excludedSyllables, $code));
  38.  
  39. return $code;
  40. }
  41.  
  42. function fastFuckedCaptcha(array $dictionary, string $excludedSyllables, int $length): string
  43. {
  44. $captcha = '';
  45. $previousCharacter = '';
  46. $generatedLength = 0;
  47.  
  48. while ($generatedLength < $length) {
  49. $randomCharacter = $dictionary[array_rand($dictionary)];
  50.  
  51. if(preg_match($excludedSyllables, $previousCharacter . $randomCharacter))
  52. continue;
  53.  
  54. $captcha .= $randomCharacter;
  55. $previousCharacter = $randomCharacter;
  56. $generatedLength++;
  57. }
  58.  
  59. return $captcha;
  60. }
  61.  
  62.  
  63. $t0 = microtime(true);
  64.  
  65. for ($i = 0; $i < 100000; $i++)
  66. fuckedCaptcha($str, $excludesRegex, $length);
  67.  
  68. $t1 = microtime(true);
  69.  
  70. for ($i = 0; $i < 100000; $i++)
  71. fastCaptcha($dictionaryArray, $indexedExcludes, $length);
  72.  
  73. $t2 = microtime(true);
  74.  
  75. for ($i = 0; $i < 100000; $i++)
  76. fastFuckedCaptcha($dictionaryArray, $excludesRegex, $length);
  77.  
  78. $t3 = microtime(true);
  79.  
  80. echo "regexp : " . ($t1 - $t0) . "\n";
  81. echo "array index: " . ($t2 - $t1) . "\n";
  82. echo "regexp again: " . ($t3 - $t2) . "\n";
Success #stdin #stdout 0.5s 26240KB
stdin
Standard input is empty
stdout
regexp     : 0.27384805679321
array index: 0.062637090682983
regexp again: 0.13959193229675