Files
selima-perl/lib/php/monica/zhnum.inc.php
2026-03-10 21:31:43 +08:00

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