php实现阿拉伯数字和罗马数字相互转换的方法

这篇文章主要介绍了php实现阿拉伯数字和罗马数字相互转换的方法,涉及php字符串操作的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下,本文实例讲述了php实现阿拉伯数字和罗马数字相互转换的方法,分享给大家供大家参考,具体如下:

  1. <?php
  2. // Function that calculates the roman string to the given number:
  3. function dec2roman($f)
  4. {
  5. // Return false if either $f is not a real number,
  6. //$f is bigger than 3999 or $f is lower or equal to 0:
  7. if(!is_numeric($f) || $f > 3999 || $f <= 0) return false;
  8. // Define the roman figures:
  9. $roman = array(
  10. 'M' => 1000,
  11. 'D' => 500,
  12. 'C' => 100,
  13. 'L' => 50,
  14. 'X' => 10,
  15. 'V' => 5,
  16. 'I' => 1
  17. );
  18. // Calculate the needed roman figures:
  19. foreach($roman as $k => $v)
  20. if(($amount[$k] = floor($f / $v)) > 0)
  21. $f -= $amount[$k] * $v;
  22. // Build the string:
  23. $return = '';
  24. foreach($amount as $k => $v)
  25. {
  26. $return .= $v <= 3 ? str_repeat($k, $v) : $k . $old_k;
  27. $old_k = $k;
  28. }
  29. // Replace some spacial cases and return the string:
  30. return str_replace(array('VIV','LXL','DCD'),array('IX','XC','CM'),$return);
  31. }
  32. // echo dec2romen(1981);
  33. // Function to get the decimal value of a roman string:
  34. function roman2dec($str = '')
  35. {
  36. // Return false if not at least one letter is in the string:
  37. if(is_numeric($str)) return false;
  38. // Define the roman figures:
  39. $roman = array(
  40. 'M' => 1000,
  41. 'D' => 500,
  42. 'C' => 100,
  43. 'L' => 50,
  44. 'X' => 10,
  45. 'V' => 5,
  46. 'I' => 1
  47. );
  48. // Convert the string to an array of roman values:
  49. for($i = 0; $i < strlen($str); $i++)
  50. if(isset($roman[strtoupper($str[$i])]))
  51. $values[] = $roman[strtoupper($str[$i])];
  52. // Calculate the sum of that array:
  53. $sum = 0;
  54. while($current = current($values))
  55. {
  56. $next = next($values);
  57. $next > $current ? $sum += $next - $current + 0 * next($values) : $sum += $current;
  58. }
  59. // Return the value:
  60. return $sum;
  61. }
  62. // echo roman2dec(IX);
  63. ?>