Как да преобразуваме числова стойност в думи чрез PHP
Публикувано от Nick / Разгледано 6799 пъти / Програмиране / 17 Юни 2009
Можеби сте се сблъсквали с такава задача, но всичко което сте намирали за конвертиране на число към дума е било предвидено за английски език. Е... тогава сега е щастливият ви ден! :)
Ще Ви предоставя един PHP клас специално написан от нас за един проект върху който работехме преди около година.
class TextualNumber
{
var $units = array();
var $teens = array();
var $hundredth = array();
var $tens = array();
var $suffix = array();
function TextualNumber()
{
$this->units = array('нула', 'едно', 'две', 'три', 'четери', 'пет', 'шест', 'седем', 'осем', 'девет');
$this->teens = array('десет', 'единадесет', 'дванадесет', 'тринадесет', 'четеринадесет', 'петнадесет', 'шестнадесет', 'седемнадесет', 'осемнадесет', 'деветнадесет');
$this->hundredth = array(1=>'сто','двеста','триста','четеристотин','петстотин','шестстотин','седемстотин','осемстотин','деветстотин');
$this->tens = array(2 => 'двадесет', 'тридесет', 'четеридесет', 'петдесет', 'шестдесет', 'седемдесет', 'осемдесет', 'деветдесет');
$this->suffix = array('хиляди', 'милиона', 'милиарда', 'trillion', 'quadrillion');
}
function ToString($int)
{
if (!preg_match('#^[\d.]+$#', $int)) {
echo('Невалидни символи! Моля въведете числова стойност.');
return;
}
if (strpos($int, '.') !== false) {
$decimal = substr($int, strpos($int, '.') + 1);
$int = substr($int, 0, strpos($int, '.'));
}
$int = ltrim($int, '0');
if ($int == '') {
$int = '0';
}
if ($negative = ($int < 0)) {
$int = substr($int, 1);
}
if (strlen($int) > 18) {
echo('Числото съдържа повече от 18 цифри!');
return;
}
$orig = $int;
switch (strlen($int)) {
case '1':
$text = $this->units[$int];
break;
case '2':
if ($int{0} == '1') {
$text = $this->teens[$int{1}];
} else if ($int{1} == '0') {
$text = $this->tens[$int{0}];
if($this->flag == 3) $text = 'и '.$text;
echo $this->flag."
";
$this->flag = 0;
} else {
$text = $this->tens[$int{0}] . ' и ' . $this->units[$int{1}];
}
break;
case '3':
if ($int % 100 == 0) {
$text = $this->hundredth[$int{0}];
} else {
$int_tmp = substr($int, 1);
if($int_tmp{0} == '0' || $int_tmp{0} == '1') $add = 'и';
$this->flag = 3;
$text = $this->hundredth[$int{0}] . " $add " . $this->GetText(substr($int, 1));
}
break;
default:
$pieces = array();
$suffixIndex = 0;
$num = substr($int, -3);
if ($num > 0) {
$pieces[] = $this->GetText($num);
}
$int = substr($int, 0, -3);
while (strlen($int) > 3) {
$num = substr($int, -3);
if ($num > 0) {
$pieces[] = $this->GetText($num) . ' ' . $this->suffix[$suffixIndex];
}
$int = substr($int, 0, -3);
$suffixIndex++;
}
if (substr($int, -3) == 1)
{
$t = $this->suffix[$suffixIndex];
if($suffixIndex == 0 && $int == 1) $ending = 'а';
else $preff = 'един ';
$pieces[] = $preff . substr($t,0,-2) . $ending;
}
else
{
$pieces[] = $this->GetText(substr($int, -3)) . ' ' . $this->suffix[$suffixIndex];
}
$pieces = array_reverse($pieces);
if (count($pieces) > 1 AND strpos($pieces[count($pieces) - 1], ' и ') === false) {
$pieces[] = $pieces[count($pieces) - 1];
$pieces[count($pieces) - 2] = 'и';
}
$text = implode(' ', $pieces);
if ($negative) {
$text = 'минус ' . $text;
}
break;
}
if (!empty($decimal)) {
$pieces = array();
$decimal = preg_replace('#[^0-9]#', '', $decimal);
$text .= ' точка ' . $this->GetText($decimal);
}
return $text;
}
function GetText($int)
{
return $this->ToString($int);
}
/**
* Returns text and number for a randomly generated number.
*
* @return array Array of number and textual representation
*/
function Get()
{
$int = mt_rand(1, 99999);
return array($int, $this->ToString($int));
}
/**
* Returns currency version of a given number.
*
* @param string $int Number to convert
* @param string $major Word to use for left hand side of decimal point
* @param string $minor Word to use for right hand side of decimal point
* @return string Resulting string
*/
function GetCurrency($int, $major = 'pound', $minor = 'pence')
{
if (strpos($int, '.') !== false) {
$left = substr($int, 0, strpos($int, '.'));
$right = substr($int, strpos($int, '.') + 1);
// Plural $major ?
if ((int)abs($left) != 1) {
$major .= 's';
}
$text = $this->GetText($left) . " $major and " . $this->GetText($right) . " $minor";
} else {
$text = $this->GetText($int) . " $major";
}
return $text;
}
}
А ето и как може да го използвате:
header('Content-type: text/html; charset=UTF-8');
require_once("number2textBG.class.php");
if($_POST[submit])
{
$t2n = new TextualNumber;
$txt2n = $_POST[number].' - ';
$txt2n .= $t2n->GetText($_POST[number]);
}
echo '<form method="post" action="">
<input type="text" name="number" value="" />
<input type="submit" name="submit" value="Submit" />
</form>';
echo $txt2n;
Не забравяйте да изпробвате демото.
Търсене в статиите
Loading