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

yipeiwu_com5年前PHP代码库

本文实例讲述了php实现阿拉伯数字和罗马数字相互转换的方法。分享给大家供大家参考。具体如下:

<?php
// Function that calculates the roman string to the given number:
function dec2roman($f)
{
 // Return false if either $f is not a real number, 
 //$f is bigger than 3999 or $f is lower or equal to 0:  
  if(!is_numeric($f) || $f > 3999 || $f <= 0) return false;
 // Define the roman figures:
  $roman = array(
  'M' => 1000,
  'D' => 500,
  'C' => 100,
  'L' => 50,
  'X' => 10,
  'V' => 5,
  'I' => 1
  );
 // Calculate the needed roman figures:
  foreach($roman as $k => $v)
  if(($amount[$k] = floor($f / $v)) > 0)
  $f -= $amount[$k] * $v;
 // Build the string:
  $return = '';
  foreach($amount as $k => $v)
  {
   $return .= $v <= 3 ? str_repeat($k, $v) : $k . $old_k;
   $old_k = $k;  
  }
 // Replace some spacial cases and return the string:
  return str_replace(array('VIV','LXL','DCD'),array('IX','XC','CM'),$return);
}
// echo dec2romen(1981);
// Function to get the decimal value of a roman string:
function roman2dec($str = '')
{
 // Return false if not at least one letter is in the string:
  if(is_numeric($str)) return false;
 // Define the roman figures:
  $roman = array(
  'M' => 1000,
  'D' => 500,
  'C' => 100,
  'L' => 50,
  'X' => 10,
  'V' => 5,
  'I' => 1
  );
 // Convert the string to an array of roman values:
  for($i = 0; $i < strlen($str); $i++) 
  if(isset($roman[strtoupper($str[$i])]))
  $values[] = $roman[strtoupper($str[$i])];
 // Calculate the sum of that array:
  $sum = 0;
  while($current = current($values))
  {
   $next = next($values);
   $next > $current ? $sum += $next - $current + 0 * next($values) : $sum += $current;
  }
 // Return the value:
  return $sum;
}
// echo roman2dec(IX);  
?>

希望本文所述对大家的php程序设计有所帮助。

相关文章

PHP提取中文首字母

复制代码 代码如下:<?     function pykey( $py_key)   &...

php用户注册时常用的检验函数实例总结

本文实例总结了php用户注册时常用的检验函数。分享给大家供大家参考。具体分析如下: php用户注册时常用的一些常用检验函数总结,包括有检测提交的数据是否符合用户名格式,检测参数的值是否相...

使用Linux五年积累的一些经验技巧

1. bash中的$相关参数 复制代码 代码如下:$0 - 表示当前文件名  $* - 以空格分离所有参数,形成一个字符串  $@ - 以空格分离所有参数,形成一个字...

PHP实现向关联数组指定的Key之前插入元素的方法

本文实例讲述了PHP实现向关联数组指定的Key之前插入元素的方法。分享给大家供大家参考,具体如下: PHP 关联数组可以通过三种方式插入新元素: 1. $array[$insert_ke...

PHP实现正则表达式分组捕获操作示例

PHP实现正则表达式分组捕获操作示例

本文实例讲述了PHP实现正则表达式分组捕获操作。分享给大家供大家参考,具体如下: 经过测试,发现php正则表达式获取分组捕获是从$0开始,而平时工作中JavaScript中的正则是$1....