近期一個小項目須要用到公式運算, 因此就進行一些瞭解,如下內容均屬於我的經驗。php
在PHP中實現公式表達式四則運算大概有兩種方法:算法
1)使用系統函數evalexpress
2)將表達式轉換成逆波蘭表達式進行計算。數組
<?php //使用系統函數eval $str = 'L*((k-J)-(C+k))/M'; $param = array('L' => 0.5, 'k' => 2, 'J' => 1, 'C' => 6, 'M' => 4); $str2 = ''; for($i = 0; $i < strlen($str); $i++) { $tmp = substr($str, $i, 1); if (array_key_exists($tmp, $param)) { $str2 .= $param[$tmp]; } else { $str2 .= $tmp; } } eval("\$str = $str2;"); printf('%5.2d', $str); /*End of php*/
<?php /** * math_rpn * * 實現逆波蘭式算法 * * @author sparkHuang 260558820@qq.com * @version RPN 1.0.0 * */ class math_rpn { //初始的計算表達式 private $_expression = ''; //處理後的逆波蘭表達式 private $_rpnexp = array(); //模擬棧結構的數組 private $_stack = array('#'); //正則判斷 //private $_reg = '/^([A-Za-z0-9\(\)\+\-\*\/])*$/'; //優先級 private $_priority = array('#' => 0, '(' => 10, '+' => 20, '-' => 20, '*' => 30, '/' => 30); //四則運算 private $_operator = array('(', '+', '-', '*', '/', ')'); public function __construct($expression) { $this->_init($expression); } private function _init($expression) { $this->_expression = $expression; } public function exp2rpn() { $len = strlen($this->_expression); for($i = 0; $i < $len; $i++) { $char = substr($this->_expression, $i, 1); if ($char == '(') { $this->_stack[] = $char; continue; } else if ( ! in_array($char, $this->_operator)) { $this->_rpnexp[] = $char; continue; } else if ($char == ')') { for($j = count($this->_stack); $j >= 0; $j--) { $tmp = array_pop($this->_stack); if ($tmp == "(") { break; } else { $this->_rpnexp[] = $tmp; } } continue; } else if ($this->_priority[$char] <= $this->_priority[end($this->_stack)]) { $this->_rpnexp[] = array_pop($this->_stack); $this->_stack[] = $char; continue; } else { $this->_stack[] = $char; continue; } } for($i = count($this->_stack); $i >= 0; $i--) { if (end($this->_stack) == '#') break; $this->_rpnexp[] = array_pop($this->_stack); } return $this->_rpnexp; } } $expression = "(A*(B+C)-E+F)*G"; var_dump($expression); $mathrpn = new math_rpn($expression); var_dump($mathrpn->exp2rpn()); /*End of php*/