fork(1) download
  1. <?php
  2.  
  3. function words_to_number($data) {
  4. // Replace all number words with an equivalent numeric value
  5. $data = strtr(
  6. $data,
  7. 'zero' => '0',
  8. 'a' => '1',
  9. 'one' => '1',
  10. 'two' => '2',
  11. 'three' => '3',
  12. 'four' => '4',
  13. 'five' => '5',
  14. 'six' => '6',
  15. 'seven' => '7',
  16. 'eight' => '8',
  17. 'nine' => '9',
  18. 'ten' => '10',
  19. 'eleven' => '11',
  20. 'twelve' => '12',
  21. 'thirteen' => '13',
  22. 'fourteen' => '14',
  23. 'fifteen' => '15',
  24. 'sixteen' => '16',
  25. 'seventeen' => '17',
  26. 'eighteen' => '18',
  27. 'nineteen' => '19',
  28. 'twenty' => '20',
  29. 'thirty' => '30',
  30. 'forty' => '40',
  31. 'fourty' => '40', // common misspelling
  32. 'fifty' => '50',
  33. 'sixty' => '60',
  34. 'seventy' => '70',
  35. 'eighty' => '80',
  36. 'ninety' => '90',
  37. 'hundred' => '100',
  38. 'thousand' => '1000',
  39. 'million' => '1000000',
  40. 'billion' => '1000000000',
  41. 'and' => '',
  42. )
  43. );
  44.  
  45. // Coerce all tokens to numbers
  46. $parts = array_map(
  47. function ($val) {
  48. return floatval($val);
  49. },
  50. preg_split('/[\s-]+/', $data)
  51. );
  52.  
  53. $stack = new SplStack; // Current work stack
  54. $sum = 0; // Running total
  55. $last = null;
  56.  
  57. foreach ($parts as $part) {
  58. if (!$stack->isEmpty()) {
  59. // We're part way through a phrase
  60. if ($stack->top() > $part) {
  61. // Decreasing step, e.g. from hundreds to ones
  62. if ($last >= 1000) {
  63. // If we drop from more than 1000 then we've finished the phrase
  64. $sum += $stack->pop();
  65. // This is the first element of a new phrase
  66. $stack->push($part);
  67. } else {
  68. // Drop down from less than 1000, just addition
  69. // e.g. "seventy one" -> "70 1" -> "70 + 1"
  70. $stack->push($stack->pop() + $part);
  71. }
  72. } else {
  73. // Increasing step, e.g ones to hundreds
  74. $stack->push($stack->pop() * $part);
  75. }
  76. } else {
  77. // This is the first element of a new phrase
  78. $stack->push($part);
  79. }
  80.  
  81. // Store the last processed part
  82. $last = $part;
  83. }
  84.  
  85. return $sum + $stack->pop();
  86. }
  87.  
  88. // test
  89. $words = 'five';
  90. echo words_to_number($words);
Success #stdin #stdout 0.02s 23740KB
stdin
Standard input is empty
stdout
5