0

In PHP, how can I convert a string that is a spelled out number like "forty two" or "forty-two" or "five thousand" or "one" and convert to a string made out of digits like "42" or "42" or "5000" or "1".

I have found this to convert certain numbers, it has an upper limit, into the spelled out versions, but I am trying to do the opposite.

<?php
/** 
*  Function:   convert_number 
*
*  Description: 
*  Converts a given integer (in range [0..1T-1], inclusive) into 
*  alphabetical format ("one", "two", etc.)
*
*  @int
*
*  @return string
*
*/ 
function convert_number($number) 
{ 
if (($number < 0) || ($number > 999999999)) 
{ 
throw new Exception("Number is out of range");
} 

$Gn = floor($number / 1000000);  /* Millions (giga) */ 
$number -= $Gn * 1000000; 
$kn = floor($number / 1000);     /* Thousands (kilo) */ 
$number -= $kn * 1000; 
$Hn = floor($number / 100);      /* Hundreds (hecto) */ 
$number -= $Hn * 100; 
$Dn = floor($number / 10);       /* Tens (deca) */ 
$n = $number % 10;               /* Ones */ 

$res = ""; 

if ($Gn) 
{ 
    $res .= convert_number($Gn) . " Million"; 
} 

if ($kn) 
{ 
    $res .= (empty($res) ? "" : " ") . 
        convert_number($kn) . " Thousand"; 
} 

if ($Hn) 
{ 
    $res .= (empty($res) ? "" : " ") . 
        convert_number($Hn) . " Hundred"; 
} 

$ones = array("", "One", "Two", "Three", "Four", "Five", "Six", 
    "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", 
    "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", 
    "Nineteen"); 
$tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", 
    "Seventy", "Eigthy", "Ninety"); 

if ($Dn || $n) 
{ 
    if (!empty($res)) 
    { 
        $res .= " and "; 
    } 

    if ($Dn < 2) 
    { 
        $res .= $ones[$Dn * 10 + $n]; 
    } 
    else 
    { 
        $res .= $tens[$Dn]; 

        if ($n) 
        { 
            $res .= "-" . $ones[$n]; 
        } 
    } 
} 

if (empty($res)) 
{ 
    $res = "zero"; 
} 

return $res; 
} 


$cheque_amt = 8747484 ; 
try
{
echo convert_number($cheque_amt);
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>

I would greatly appreciate any and all help in figuring out how to do this as I am stumped.

Right now, I am considering using PHP's is_numeric() to detect if it is numeric, but then how do I convert it to the numbers?

Update: Here is an even better example as it doesn't have a limit and can handle negative numbers. But it is doing the reverse. Can someone help me get this code to do the reverse ( convert spelled out number to digits ).

Django Johnson
  • 1,383
  • 3
  • 21
  • 40

1 Answers1

0

Is_numeric won't detect if it is numerical in text form only if it is a physical number, decimal or integer. With regards the text to number, I think this maybe a good and untouched area that you may just have to spend some time on

Liam Sorsby
  • 2,912
  • 3
  • 28
  • 51