116 lines
3.0 KiB
PHP
116 lines
3.0 KiB
PHP
<?php
|
|
// File name: zhnum.inc.php
|
|
// Description: PHP subroutines to deal with Chinese numbers
|
|
// Date: 2004-12-28
|
|
// Author: imacat <imacat@pristine.com.tw>
|
|
// Copyright: Copyright (C) 2004-2012 Pristine Communications
|
|
|
|
// This file is in UTF-8 萬國碼
|
|
|
|
// Settings
|
|
define("ZHNUM_DIG", "(?:一|二|三|四|五|六|七|八|九)");
|
|
define("ZHNUM_NUM1D", ZHNUM_DIG);
|
|
define("ZHNUM_NUM2D", ZHNUM_DIG . "?十" . ZHNUM_DIG . "?");
|
|
define("ZHNUM_NUM3D", ZHNUM_DIG . "百(?:零" . ZHNUM_DIG . "|十" . ZHNUM_DIG . "?|" . ZHNUM_DIG . "十" . ZHNUM_DIG . "?)?");
|
|
$_ZHNUM = array(
|
|
// From Chinese to Arabic number
|
|
"一" => 1,
|
|
"二" => 2,
|
|
"三" => 3,
|
|
"四" => 4,
|
|
"五" => 5,
|
|
"六" => 6,
|
|
"七" => 7,
|
|
"八" => 8,
|
|
"九" => 9,
|
|
// From Arabic number to Chinese
|
|
1 => "一",
|
|
2 => "二",
|
|
3 => "三",
|
|
4 => "四",
|
|
5 => "五",
|
|
6 => "六",
|
|
7 => "七",
|
|
8 => "八",
|
|
9 => "九",
|
|
);
|
|
|
|
// read_zhnum: Read the Chinese number
|
|
// Currently we only process 2 digit numbers, 1-99
|
|
function read_zhnum($zhnum)
|
|
{
|
|
global $_ZHNUM;
|
|
// One digit
|
|
if (preg_match("/^" . ZHNUM_DIG . "$/", $zhnum)) {
|
|
return $_ZHNUM[$zhnum];
|
|
// Two digits
|
|
} elseif (preg_match("/^(" . ZHNUM_DIG . "?)十(" . ZHNUM_DIG . "?)$/", $zhnum, $m)) {
|
|
$d2 = ($m[1] == "")? 1: $_ZHNUM[$m[1]];
|
|
$d1 = ($m[2] == "")? 0: $_ZHNUM[$m[2]];
|
|
return $d2 * 10 + $d1;
|
|
// Three digits
|
|
} elseif (preg_match("/^(" . ZHNUM_DIG . ")百((?:零" . ZHNUM_DIG . "|十" . ZHNUM_DIG . "?|" . ZHNUM_DIG . "十" . ZHNUM_DIG . "?)?)$/", $zhnum, $m)) {
|
|
$d3 = $_ZHNUM[$m[1]];
|
|
$r = 0;
|
|
if ($m[2] != "") {
|
|
$r = $m[2];
|
|
if (substr($r, 0, strlen("零")) == "零") {
|
|
$r = substr($r, strlen("零"));
|
|
}
|
|
$r = read_zhnum($r);
|
|
if (!is_integer($r)) {
|
|
return $zhnum;
|
|
}
|
|
}
|
|
return $d3 * 100 + $r;
|
|
// Bounce others -- we cannot handle them
|
|
} else {
|
|
return $zhnum;
|
|
}
|
|
}
|
|
|
|
// out_zhnum: Output the Chinese number
|
|
// Currently we only process 2 digit numbers, 1-99
|
|
function out_zhnum($num)
|
|
{
|
|
global $_ZHNUM;
|
|
// One digit
|
|
if ($num < 10) {
|
|
return $_ZHNUM[$num];
|
|
// Two digits
|
|
} elseif ($num < 100) {
|
|
$d1 = $num % 10;
|
|
$d2 = ($num - $d1) / 10;
|
|
$zhnum = "";
|
|
if ($d2 > 1) {
|
|
$zhnum .= $_ZHNUM[$d2];
|
|
}
|
|
$zhnum .= "十";
|
|
if ($d1 != 0) {
|
|
$zhnum .= $_ZHNUM[$d1];
|
|
}
|
|
return $zhnum;
|
|
// Three digits
|
|
} elseif ($num < 1000) {
|
|
$r = $num % 100;
|
|
$d3 = ($num - $r) / 100;
|
|
$zhnum = "";
|
|
$zhnum .= $_ZHNUM[$d3] . "百";
|
|
if ($r < 10 && $r != 0) {
|
|
$zhnum .= "零";
|
|
}
|
|
if ($r >= 10 && $r < 20) {
|
|
$zhnum .= "一";
|
|
}
|
|
if ($r != 0) {
|
|
$zhnum .= out_zhnum($r);
|
|
}
|
|
return $zhnum;
|
|
// Bounce others -- we cannot handle them
|
|
} else {
|
|
return $num;
|
|
}
|
|
}
|
|
|
|
?>
|