Home >Backend Development >PHP Tutorial >PHP realizes the conversion of Chinese characters into integer numbers, such as: one hundred and one is converted into 101

PHP realizes the conversion of Chinese characters into integer numbers, such as: one hundred and one is converted into 101

WBOY
WBOYOriginal
2016-07-25 08:45:241473browse
  1. test();
  2. /**
  3. * Test
  4. */
  5. function test() {
  6. echo CnToInt('一'); // 1
  7. echo CnToInt('十'); // 10
  8. echo CnToInt ('Eleven'); // 11
  9. echo CnToInt('One hundred and ten'); // 110
  10. echo CnToInt('One thousand and one'); // 1001
  11. echo CnToInt('One thousand and one hundred' Zero one'); // 10101
  12. echo CnToInt('one hundred and thirteen million and three thousand and one'); // 113003001
  13. echo CnToInt('one quadrillion'); // 11.0E+15
  14. }
  15. /**
  16. * Chinese to number
  17. * @param String $var Chinese number to be parsed
  18. * @param Int $start initial value
  19. * @return int
  20. */
  21. function CnToInt($var, $start = 0) {
  22. if (is_numeric($var)) {
  23. return $var;
  24. }
  25. if (intval($var) = == 0) {
  26. $splits = array('100 million' => 100000000, '10,000' => 10000);
  27. $chars = array('10,000' => 10000, '1000' => 1000, 'hundred' => 100, '十' => 10, '一' => 1, 'zero' => 0);
  28. $Ints = array('zero' => 0, '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5, '六' => 6, '七' => ; 7, '八' => 8, '九' => 9, '十' => 10);
  29. $var = str_replace('zero', "", $var);
  30. foreach ($splits as $key => $step) {
  31. if (strpos($var, $key)) {
  32. $strs = explode($key, $var);
  33. $start += CnToInt(array_shift($strs)) * $step;
  34. $var = join('', $strs);
  35. }
  36. }
  37. foreach ($chars as $key => $step) {
  38. if (strpos($var, $key) !== FALSE ) {
  39. $vs = explode($key, $var);
  40. if ($vs[0] === "") {
  41. $vs[0] = '一';
  42. }
  43. $start += $Ints [array_shift($vs)] * $step;
  44. $var = join('', $vs);
  45. } elseif (mb_strlen($var, 'utf-8') === 1) {
  46. $start += $Ints[$var];
  47. $var = '';
  48. break;
  49. }
  50. }
  51. return $start;
  52. } else {
  53. return intval($var);
  54. }
  55. }
Copy code

Convert to, PHP, one hundred and one


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHPMailer sends emailNext article:PHPMailer sends email