<?php
 
// Staring straight up into the sky ... oh my my
error_reporting(-1);
 
 
/* Возвращает соответствующую числу форму слова: 1 рубль, 2 рубля, 5 рублей */
function inclineWord($number, $word1, $word2, $word5) {

    $concurrence1 = '/[^123]1$|^1$/';
    $concurrence2 = '/([^1][234]|^[234])$/';
    $concurrence5 = '/((1\d)|[05-9]|([02-9][05-9]))$/';

    if (preg_match('/^000$/', $number)) {
    } elseif (preg_match($concurrence1, $number)) {
        return $word1;
    } elseif (preg_match($concurrence2, $number)) {
        return $word2;
    } elseif (preg_match($concurrence5, $number)) {
        return $word5;
    }

}

function smallNumberToText($number, $isFemale) {

    $spelling = array(
        0   =>  'ноль',                                     10  =>  'десять',       100 =>  'сто',
        1   =>  'один',         11  =>  'одиннадцать',      20  =>  'двадцать',     200 =>  'двести',
        2   =>  'два',          12  =>  'двенадцать',       30  =>  'тридцать',     300 =>  'триста',
        3   =>  'три',          13  =>  'тринадцать',       40  =>  'сорок',        400 =>  'четыреста',
        4   =>  'четыре',       14  =>  'четырнадцать',     50  =>  'пятьдесят',    500 =>  'пятьсот',
        5   =>  'пять',         15  =>  'пятнадцать',       60  =>  'шестьдесят',   600 =>  'шестьсот',
        6   =>  'шесть',        16  =>  'шестнадцать',      70  =>  'семьдесят',    700 =>  'семьсот',    
        7   =>  'семь',         17  =>  'семнадцать',       80  =>  'восемьдесят',   800 =>  'восемьсот',
        8   =>  'восемь',       18  =>  'восемнадцать',     90  =>  'девяносто',     900 =>  'девятьсот',
        9   =>  'девять',       19  =>  'девятнадцать'    
    );
 
    $femaleSpelling = array(
        1   =>  'одна',        2   =>  'две'
    );

    if ($isFemale == true) {
        $spelling = array_replace($spelling, $femaleSpelling);
    } 

    if (preg_match('/^0{1,2}/', $number) && preg_match('/[^0]/', $number)) {
            $number = implode('', preg_split("/^(0{1,2})/", $number));
    } elseif (preg_match('/000/', $number)) {
        $number = '';
        return $number;
    }

    if ($number < 10) {
        return $spelling[$number];
    } else {

        if ($number > 10) {
            $theLastNumber = preg_match("/\d$/", $number, $theLastNumber1);
            $theLastNumber2 = $spelling[implode('', $theLastNumber1)];

            $theSecondNumber = preg_match("/\d\d$/", $number, $theSecondNumber1);
            $godDamnIt1 = preg_split("/\d$/", implode('', $theSecondNumber1));

            if ((implode('', $theSecondNumber1)) > 9) {
                array_push($godDamnIt1, "0");
            }

            $theSecondNumber2 = $spelling[implode('', $godDamnIt1)];

            if ((implode('', $theSecondNumber1)) < 10) {

                if (preg_match('/^0/', implode('', $theSecondNumber1))) {
                    $imploded = implode('', preg_split('/^0/', implode('', $theSecondNumber1)));
                    $theLastNumber2 = $spelling[$imploded];
                    $theSecondNumber2 = '';
                }
            } elseif ((implode('', $theSecondNumber1)) > 10 && array_key_exists((implode('', $theSecondNumber1)), $spelling)) {
                $theSecondNumber2 = $spelling[(implode('', $theSecondNumber1))];
                $theLastNumber2 = '';
            }

            if ($number > 99) {
                $godDamnIt2 = preg_split("/\d\d$/", $number);
                array_push($godDamnIt2, "0", "0");
                $theSFirstNumber2 = $spelling[implode('', $godDamnIt2)];

                $ifMoreThanHundred = $theSFirstNumber2.' '.$theSecondNumber2.' '.$theLastNumber2;
                return $ifMoreThanHundred;
            } else {
                $ifLessThanHundred = $theSecondNumber2.' '.$theLastNumber2;
                return $ifLessThanHundred;
            }
        }
    }
}     
 
function numberToText($number) {
    
    if ($number <= 999) {
        $simpleNumbers = smallNumberToText($number, null).' '.inclineWord($number, ' рубль', ' рубля', ' рублей');
        return $simpleNumbers;
    } else {
        $match = preg_split('//', $number);
        $reverse = array_reverse($match);
        $leftDifferences = array_diff($reverse, array(''));
        $chunking = array_chunk($leftDifferences, 3);
        $count = count($chunking);   

        for ($i=0; $i < $count; $i++) { 
           $reverse1 = array_reverse($chunking[$i]);
        }
      
        $imploded1 = implode('', array_reverse($chunking[0]));
        $imploded2 = implode('', array_reverse($chunking[1]));

        $isFemale = preg_match("/(1|2)$/", $imploded2);

        if ($number > 999999) {
            $imploded3 = implode('', array_reverse($chunking[2]));
            $total2 = smallNumberToText($imploded3, null) .' '. inclineWord($imploded3, ' миллион', ' миллиона', ' миллионов') .' '. smallNumberToText($imploded2, $isFemale) .' '. inclineWord($imploded2, ' тысяча', ' тысячи', ' тысяч') .' '. smallNumberToText($imploded1, null) .' '. inclineWord($number, ' рубль', ' рубля', ' рублей')." ($number)";
            return $total2;
        }  elseif ($number > 999) {
            $total1 = smallNumberToText($imploded2, $isFemale) .' '. inclineWord($imploded2, ' тысяча', ' тысячи', ' тысяч') .' '. smallNumberToText($imploded1, null) .' '. inclineWord($number, ' рубль', ' рубля', ' рублей')." ($number)";
            return $total1;
        }
    }
}
 
/* Вызовем функцию несколько раз */
$amount1 = mt_rand(1,99999999);
$text1 = numberToText($amount1);
 
echo "На вашем счету {$text1}\n";
 
$amount2 = mt_rand(1,99999999);
$text2 = numberToText($amount2);
 
echo "На вашем счету {$text2}\n";
 
$amount3 = mt_rand(1,99999999);
$text3 = numberToText($amount3);
 
echo "На вашем счету {$text3}\n";
 
$amount4 = mt_rand(1,99999999);
$text4 = numberToText($amount4);
 
echo "На вашем счету {$text4}\n";