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 ).