Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting words to numbers in PHP

Tags:

I am trying to convert numerical values written as words into integers. For example, "iPhone has two hundred and thirty thousand seven hundred and eighty three apps" would become "iPhone as 230783 apps"

Before i start coding, I would like to know if any function / code exists for this conversion.

like image 823
user132513 Avatar asked Jul 03 '09 02:07

user132513


People also ask

How to convert a string into number in PHP?

Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. echo number_format( $num , 2);

How to convert value to integer in PHP?

PHP Casting Strings and Floats to IntegersThe (int), (integer), or intval() function are often used to convert a value to an integer.

How do I change to digits in Word?

php function word_digit($word) { $warr = explode(';',$word); $result = ''; foreach($warr as $value){ switch(trim($value)){ case 'zero': $result . = '0'; break; case 'one': $result . = '1'; break; case 'two': $result . = '2'; break; case 'three': $result .

How can I print the amount of words in PHP?

php /** * Created by PhpStorm. 10 : 100; $number = floor($no % $divider); $no = floor($no / $divider); $i += ($divider == 10) ? 1 : 2; if ($number) { $plural = (($counter = count($str)) && $number > 9) ? 's' : null; $hundred = ($counter == 1 && $str[0]) ?


2 Answers

There are lots of pages discussing the conversion from numbers to words. Not so many for the reverse direction. The best I could find was some pseudo-code on Ask Yahoo. See http://answers.yahoo.com/question/index?qid=20090216103754AAONnDz for a nice algorithm:

Well, overall you are doing two things: Finding tokens (words that translates to numbers) and applying grammar. In short, you are building a parser for a very limited language.

The tokens you would need are:

POWER: thousand, million, billion
HUNDRED: hundred
TEN: twenty, thirty... ninety
UNIT: one, two, three, ... nine,
SPECIAL: ten, eleven, twelve, ... nineteen

(drop any "and"s as they are meaningless. Break hyphens into two tokens. That is sixty-five should be processed as "sixty" "five")

Once you've tokenized your string, move from RIGHT TO LEFT.

  1. Grab all the tokens from the RIGHT until you hit a POWER or the whole string.

  2. Parse the tokens after the stop point for these patterns:

    SPECIAL
    TEN
    UNIT
    TEN UNIT
    UNIT HUNDRED
    UNIT HUNDRED SPECIAL
    UNIT HUNDRED TEN
    UNIT HUNDRED UNIT
    UNIT HUNDRED TEN UNIT

    (This assumes that "seventeen hundred" is not allowed in this grammar)

    This gives you the last three digits of your number.

  3. If you stopped at the whole string you are done.

  4. If you stopped at a power, start again at step 1 until you reach a higher POWER or the whole string.

like image 120
John Kugelman Avatar answered Oct 06 '22 15:10

John Kugelman


Old question, but for anyone else coming across this I had to write up a solution to this today. The following takes a vaguely similar approach to the algorithm described by John Kugelman, but doesn't apply as strict a grammar; as such it will permit some weird orderings, e.g. "one hundred thousand and one million" will still produce the same as "one million and one hundred thousand" (1,100,000). Invalid bits (e.g. misspelled numbers) will be ignored, so the consider the output on invalid strings to be undefined.

Following user132513's comment on joebert's answer, I used Pear's Number_Words to generate test series. The following code scored 100% on numbers between 0 and 5,000,000 then 100% on a random sample of 100,000 numbers between 0 and 10,000,000 (it takes to long to run over the whole 10 billion series).

/**  * Convert a string such as "one hundred thousand" to 100000.00.  *  * @param string $data The numeric string.  *  * @return float or false on error  */ function wordsToNumber($data) {     // Replace all number words with an equivalent numeric value     $data = strtr(         $data,         array(             'zero'      => '0',             'a'         => '1',             'one'       => '1',             'two'       => '2',             'three'     => '3',             'four'      => '4',             'five'      => '5',             'six'       => '6',             'seven'     => '7',             'eight'     => '8',             'nine'      => '9',             'ten'       => '10',             'eleven'    => '11',             'twelve'    => '12',             'thirteen'  => '13',             'fourteen'  => '14',             'fifteen'   => '15',             'sixteen'   => '16',             'seventeen' => '17',             'eighteen'  => '18',             'nineteen'  => '19',             'twenty'    => '20',             'thirty'    => '30',             'forty'     => '40',             'fourty'    => '40', // common misspelling             'fifty'     => '50',             'sixty'     => '60',             'seventy'   => '70',             'eighty'    => '80',             'ninety'    => '90',             'hundred'   => '100',             'thousand'  => '1000',             'million'   => '1000000',             'billion'   => '1000000000',             'and'       => '',         )     );      // Coerce all tokens to numbers     $parts = array_map(         function ($val) {             return floatval($val);         },         preg_split('/[\s-]+/', $data)     );      $stack = new SplStack; // Current work stack     $sum   = 0; // Running total     $last  = null;      foreach ($parts as $part) {         if (!$stack->isEmpty()) {             // We're part way through a phrase             if ($stack->top() > $part) {                 // Decreasing step, e.g. from hundreds to ones                 if ($last >= 1000) {                     // If we drop from more than 1000 then we've finished the phrase                     $sum += $stack->pop();                     // This is the first element of a new phrase                     $stack->push($part);                 } else {                     // Drop down from less than 1000, just addition                     // e.g. "seventy one" -> "70 1" -> "70 + 1"                     $stack->push($stack->pop() + $part);                 }             } else {                 // Increasing step, e.g ones to hundreds                 $stack->push($stack->pop() * $part);             }         } else {             // This is the first element of a new phrase             $stack->push($part);         }          // Store the last processed part         $last = $part;     }      return $sum + $stack->pop(); } 
like image 42
El Yobo Avatar answered Oct 06 '22 14:10

El Yobo