Я взял на себя смелость переписать и очистить вашу функцию, добавив одну важную часть: преобразование из
(a) One тысяча девятьсот девяносто шесть в (b ) Девятнадцатьсот девяносто шесть.
Теперь функция принимает необязательный второй аргумент $year
. Если установлено значение true
, оно вернет (b) , иначе (a) .
numberTowords(1996)
даст (a)
numberTowords(1996,true)
даст (b)
Комментарии в коде показывают, что я изменил
function numberTowords($num,$year=false){
$num = str_replace(array(',', ' '), '' , trim($num));
if($num==='')return false;
$num = (int) $num;
$words = [];
$list=[
1=>['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
2=>['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred'],
3=>['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion','octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion','quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion']
];
//$levels = number of parts of 3
$levels = ceil(strlen($num)/3);
if($levels===0)return false;
//$parts = parts of 3, first one left-padded with zeros
$parts = str_split(substr('00' . $num, -$levels*3), 3);
$part_count=count($parts);
//THE IMPORTANT YEAR BIT
//only if year-flag = true
//only if no more then 2 parts
//only if year < 9999
// EXAMPLE: 1986
$change = false; //<< === added flag
if($year===true && $part_count===2 && $num<9999){
//get the first digit of last part (ex: 9)
$x=substr($parts[$part_count-1],0,1);
//if first digit = 0 : skip
//else: remove from last part and add to part before
// ex: 001 => 0019 and 986 => 86
if($x!=='0'){
$parts[$part_count-2]=$parts[$part_count-2].$x;
$parts[$part_count-1]=substr($parts[$part_count-1],1);
}
}
//LOOP THE PARTS
for ($i=0; $i < $part_count; $i++) {
$w=[];
//get the (int) of part
$part_num=(int)$parts[$i];
//HUNDREDS
if($part_num >= 100){
$w[]=$list[1][(int)substr($parts[$i],0,1)];
$w[]=$list[2][10];
}
//TENS and SINGLES
$remainder=$part_num%100;
if($remainder>19){
$w[]=$list[2][floor($remainder/10)];
$w[]=$list[1][$remainder%10];
}
else{
$w[]=$list[1][$remainder];
}
// << TEST FOR FLAG
if($change===true && $i===0)
$w[]=$list[2][10];
else
$w[]=$list[3][$part_count - $i -1];
$words[]=implode(' ',$w);
} //end for loop
return implode(' ', $words);
}