/ PHP

PHP实现汉字转数字

写了一个晚上,查了半天资料,终于搞定……

H_table = array (); } function put($key, $value) { if (!array_key_exists($key, $this->H_table)) { $this->H_table[$key] = $value; return null; } else { $tempValue = $this->H_table[$key]; $this->H_table[$key] = $value; return $tempValue; } } function clear() { $this->H_table = null; $this->H_table = array (); } function containsValue($value) { while ($curValue = current($this->H_table)) { if ($curValue == $value) { return true; } next($this->H_table); } return false; } function containsKey($key) { if (array_key_exists($key, $this->H_table)) { return true; } else { return false; } } function get($key) { if (array_key_exists($key, $this->H_table)) return $this->H_table[$key]; else return null; } function isEmpty() { return (count($this->H_table) == 0); } function size() { return count($this->H_table); } function remove($key) { $temp_table = array (); if (array_key_exists($key, $this->H_table)) { $tempValue = $this->H_table[$key]; while ($curValue = current($this->H_table)) { if (!(key($this->H_table) == $key)) $temp_table[key($this->H_table)] = $curValue; next($this->H_table); } $this->H_table = null; $this->H_table = $temp_table; return $tempValue; } else return null; } function toString() { print_r($this->H_table); } } class hz2sz { private $hz; private $hzsz; private $hzradix; function __construct() { $this->hz = array("零","一","二","三","四","五","六","七","八","九"); $this->hzradix = new HashTable(); $this->hzsz = new HashTable(); for($i=0;$ihz);$i++) { $this->hzsz->put($this->hz[$i],$i); } $this->hzradix->put("十",10); $this->hzradix->put("百",100); $this->hzradix->put("千",1000); $this->hzradix->put("万",10000); $this->hzradix->put("亿",100000000); } public function transform($src) { $tmp1 = explode('亿',$src); if(count($tmp1)==2) { return $this->exchange2($tmp1[0]) * $this->hzradix->get("亿") + $this->exchange2($tmp1[1]); } else { return $this->exchange2($tmp1[0]); } } private function exchange2($src) { $tmp1 = explode('万',$src); if(count($tmp1)==2) { return $this->exchange($tmp1[0]) * $this->hzradix->get("万") + $this->exchange($tmp1[1]); } else { return $this->exchange($tmp1[0]); } } private function exchange($src) { $bg = 0; for($i=0;$ihzsz->containsKey($c1)) { if($c1 == "零") { continue; } if($i + 1 < mstrlen($src)) { $c2 = mb_substr($src,$i+1,1,'utf-8'); if($this->hzradix->containsKey($c2)) { $bg += $this->hzsz->get($c1) * $this->hzradix->get($c2); } } else { $bg += $this->hzsz->get($c1); } } else if($i == 0 && $c1=="十" ¦¦ $i>0 && $c1=="十" && mb_substr($src,$i-1,1,'utf-8')=="零") { $bg += 10; } } return $bg; } } function mstrlen($string) { preg_match_all("/./us", $string, $match); return count($match[0]); } //==========使用方法============== $hz2sz = new hz2sz(); echo $hz2sz->transform("十三亿零十五万零三百一十二"); ?>
PHP实现汉字转数字
Share this