2013-06-25 123 views
0

在PHP中,如何将字符串转换为拼写出来的数字,例如“四十二”或“四十二”或“五千”或“一”以及转换为由数字如“42”或“42”或“5000”或“1”组成的字符串。将数字字符串/字母数字转换为PHP中的数字

我发现这个将某些数字,它有一个上限,转换成拼写的版本,但我试图做相反的事情。

<?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(); 
} 
?> 

我将非常感谢任何和所有帮助,在搞清楚如何做到这一点,因为我难倒了。

现在,我正在考虑使用PHP的is_numeric()来检测它是否是数字,但是如何将它转换为数字?

更新:Here是一个更好的例子,因为它没有限制,可以处理负数。但它正在做相反的事情。有人可以帮我弄这个代码做相反的事情(把拼出的数字转换成数字)。

+1

http://stackoverflow.com/questions/13651340/converting-words-to-numbers-in -php-ii?rq = 1 –

回答

0

只有当它是一个物理数字,十进制或整数时,Is_numeric才会检测它是否为文本形式的数字。关于文本的数量,我认为这可能是一个很好的和未触及的领域,你可能只需要花一些时间

+0

看起来我错了字符串到数字,虽然这将是一个很好的项目! –

相关问题