php实现简单四则运算

<?php
$str = '(1+2*(3+5)/4)*(3+(5-4)*2)';
echo compute($str);

//四则运算
function compute($str) {
    $numsStack = array ();
    $operStack = array ();
   
    $len = strlen ( $str );
    $nums = '';
    for($i = 0; $i < $len; $i ++) {
        $ch = $str [$i];
        if ($ch == '(') {
            array_push ( $operStack, $ch );
        } else if ($ch == ')') {
            while ( ($oper = array_pop ( $operStack )) != '(' ) {
                $num1 = array_pop ( $numsStack );
                $num2 = array_pop ( $numsStack );
                $res = opertion ( $num1, $oper, $num2 );
                array_push ( $numsStack, $res );
            }
        } else if (isOper ( $ch )) {
            if (empty ( $operStack )) {
                array_push ( $operStack, $ch );
            } else {
                $chPRI = PRI ( $ch );
                $stackPRI = PRI ( $operStack [count ( $operStack ) - 1] );
                if ($chPRI <= $stackPRI) {
                    $num1 = array_pop ( $numsStack );
                    $num2 = array_pop ( $numsStack );
                    $oper = array_pop ( $operStack );
                    $res = opertion ( $num1, $oper, $num2 );
                    array_push ( $numsStack, $res );
                    array_push ( $operStack, $ch );
                } else {
                    array_push ( $operStack, $ch );
                }
            }
        } else {
            $nums .= $ch;
            if ($i == $len - 1) {
                array_push ( $numsStack, $nums );
            } else {
                if (isOper ( $str [$i + 1] )) {
                    array_push ( $numsStack, $nums );
                    $nums = '';
                }
            }
        }
    }
   
    while ( ! empty ( $operStack ) ) {
        $num1 = array_pop ( $numsStack );
        $num2 = array_pop ( $numsStack );
        $oper = array_pop ( $operStack );
        $res = opertion ( $num1, $oper, $num2 );
        array_push ( $numsStack, $res );
    }
    return array_pop($numsStack);
}

//判断是否是符号
function isOper($str) {
    if (strchr ( '+-*/()', $str )) {
        return true;
    } else {
        return false;
    }
}

//计算
function opertion($n1, $oper, $n2) {
    switch ($oper) {
        case '+' :
            $res = $n1 + $n2;
            break;
        case '-' :
            $res = $n2 - $n1;
            break;
        case '*' :
            $res = $n1 * $n2;
            break;
        case '/' :
            $res = $n2 / $n1;
            break;
    }
    return $res;
}

//优先级
function PRI($oper) {
    if ($oper == '+' || $oper == '-') {
        $res = 1;
    }
    if ($oper == '*' || $oper == '/') {
        $res = 2;
    }
    return $res;
}

posted @ 2013-05-21 13:06  yangqing_fly  阅读(859)  评论(0编辑  收藏  举报