This article mainly introduced PHP implementation of the simple arithmetic calculator function, combined with an example of PHP based on the implementation of the stack of expression arithmetic function, the need for friends can refer to, hope to help everyone.
The structure of the stack can be used here, because the PHP array "natural" has the characteristics of the stack, where the array is used directly. Of course, you can use the stack structure to write, the same reason.
Predecessor (Polish scientist) computes the four expression with parentheses, using the inverse Polish algorithm (suffix expression). What a god!! In fact code is not difficult, difficult is the guidance of the algorithm, to understand the algorithm before coding.
<?php$num_arr = Array ();//Declare the number stack $op_arr = array ();//declare symbol stack $STR = "10+6*2-18/2-2";p reg_match_all ('/./', $str, $arr);// The operation string is decomposed into a $arr array $str_arr = $arr [0]; $length = count ($str _arr); $pre _num = ";//start into stack for ($i =0; $i < $length; $i + +) {$val = $str _arr[$i]; The number if (Is_numeric ($val)) {$pre _num. = $val;//The case of the next character may also be a number (multi-digit) if ($i +1>= $length | | isoper ($STR _arr[$i +1] ) {//Next is operator or head, then plug the number into the digital stack Array_push ($num _arr, $pre _num); $pre _num = "; }//symbol to determine priority, choose whether to stack} else if (Isoper ($val)) {if (count ($op _arr) >0) {//Judgment priority, as long as it is not greater than the priority of the top of the symbol stack, starts the calculation until the priority is greater than the top of the stack , the operator is then put into the stack while (end ($op _arr) && priority ($val) <= priority (end ($op _arr)) {Calc ($num _arr, $op _arr); }} array_push ($op _arr, $val); }}//echo ' <pre> ';//print_r ($num _arr);//print_r ($op _arr);//The remaining while in the calculation stack (count ($num _arr) >0) {Calc ($num _ Arr, $op _arr); if (count ($num _arr) ==1) {$result = Array_pop ($num _arr); Break }}echo $str, ' = ', $result;//calculate, get the numberStack of two numbers, the operator function for the top of the symbol stack, calc (& $num _arr, & $op _arr) {if (count ($num _arr) >0) {$num 1 = array_pop ($num _arr); $num 2 = Array_pop ($num _arr); $op = Array_pop ($op _arr); if ($op = = ' * ') $re = $num 1* $num 2; if ($op = = '/') $re = $num 2/$num 1;//Here Note the order, the stack is advanced and then out, so $num2 is the divisor if ($op = = ' + ') $re = $num 1 $num if ($op = = '-') $re = $num 2-$num 1; Array_push ($num _arr, $re); }}//Gets the priority function order ($STR) {if ($str = = ' * ' | | $str = = '/') {return 1; } else {return 0; }}//determines whether the operator function Isoper ($oper) {$oper _array = array (' + ', '-', ' * ', '/'); if (In_array ($oper, $oper _array)) {return true; } return false;}
Operation Result:
10+6*2-18/2-2 = 11