Note that there are some explanatory texts on larger screens.

plurals
  1. POconverting-words-to-numbers-in-php II
    primarykey
    data
    text
    <p>There is a great function here <a href="https://stackoverflow.com/questions/1077600/converting-words-to-numbers-in-php">Converting words to numbers in PHP</a> from El Yobo. But I have the problem that the string must begin with a written number. How can convert e.g. "iPhone has two hundred and thirty thousand, seven hundred and eighty-three apps" ?</p> <p>The explained function:</p> <pre><code>function wordsToNumber($data) { // Replace all number words with an equivalent numeric value $data = strtr( $data, array( 'zero' =&gt; '0', 'a' =&gt; '1', 'one' =&gt; '1', 'two' =&gt; '2', 'three' =&gt; '3', 'four' =&gt; '4', 'five' =&gt; '5', 'six' =&gt; '6', 'seven' =&gt; '7', 'eight' =&gt; '8', 'nine' =&gt; '9', 'ten' =&gt; '10', 'eleven' =&gt; '11', 'twelve' =&gt; '12', 'thirteen' =&gt; '13', 'fourteen' =&gt; '14', 'fifteen' =&gt; '15', 'sixteen' =&gt; '16', 'seventeen' =&gt; '17', 'eighteen' =&gt; '18', 'nineteen' =&gt; '19', 'twenty' =&gt; '20', 'thirty' =&gt; '30', 'forty' =&gt; '40', 'fourty' =&gt; '40', // common misspelling 'fifty' =&gt; '50', 'sixty' =&gt; '60', 'seventy' =&gt; '70', 'eighty' =&gt; '80', 'ninety' =&gt; '90', 'hundred' =&gt; '100', 'thousand' =&gt; '1000', 'million' =&gt; '1000000', 'billion' =&gt; '1000000000', 'and' =&gt; '', ) ); // 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-&gt;isEmpty()) { // We're part way through a phrase if ($stack-&gt;top() &gt; $part) { // Decreasing step, e.g. from hundreds to ones if ($last &gt;= 1000) { // If we drop from more than 1000 then we've finished the phrase $sum += $stack-&gt;pop(); // This is the first element of a new phrase $stack-&gt;push($part); } else { // Drop down from less than 1000, just addition // e.g. "seventy one" -&gt; "70 1" -&gt; "70 + 1" $stack-&gt;push($stack-&gt;pop() + $part); } } else { // Increasing step, e.g ones to hundreds $stack-&gt;push($stack-&gt;pop() * $part); } } else { // This is the first element of a new phrase $stack-&gt;push($part); } // Store the last processed part $last = $part; } return $sum + $stack-&gt;pop(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload