php实现混合四则运算函数

因为php函数 eval() 过于危险,为了方便计算字符串格式的运算公式,所以对 jiaych大拿的函数进行了改编,基本实现了类似 eval() 函数计算功能。贴代码:

/*******************四则运算计算器********************/
function maths($exp){
	$arr_exp = [];
	for($i=0;$i
function calculator( $exp ){
	$arr_n  = [];
	$arr_op = [];
	while( ($s = array_pop( $exp )) != '' ){
		if( $s == '(' ){
			$temp = []; 
			$quote = 1; 
			$endquote = 0;
			while( ($t = array_pop($exp)) != '' ){
				if( $t == '(' ){
					$quote++;
				}
				if( $t == ')' ){
					$endquote++;
					if( $quote == $endquote ){
						break;
					}
				}
				array_push($temp, $t);
			}
			$temp = array_reverse($temp);
			array_push($arr_n, calculator($temp) );
		}else if( $s == '*' || $s == '/'){
			$n2 = array_pop($exp);
			if( $n2 == '(' ){
				$temp = array(); 
				$quote = 1; 
				$endquote = 0;
				while( ($t = array_pop($exp)) != '' ){
					if( $t == '(' ){
						$quote++;
					}
					if( $t == ')' ){
						$endquote++;
						if( $quote == $endquote )
							break;
					}
					array_push($temp, $t);
				}
				$temp = array_reverse($temp);
				$n2 = calculator($temp);
			}
			$op = $s;
			$n1 = array_pop($arr_n);
			switch ($op) {
				case '+':
					$result = $n1 + $n2;
				break;
				case '-':
					$result = $n1 - $n2;
				break;
				case '*':
					$result = $n1 * $n2;
				break;
				case '/':
					$result = $n1 / $n2;
				break;
			}
			array_push($arr_n, $result);
		}else if( $s == '+' || $s == '-' ){
			array_push($arr_op, $s);
		}else{
			array_push($arr_n, $s);
		}
	}
	$n2 = array_pop($arr_n);
	while( ($op = array_pop($arr_op)) != '' ){
		$n1 = array_pop($arr_n);
		switch ($op) {
			case '+':
				$n2 = $n1 + $n2;
			break;
			case '-':
				$n2 = $n1 - $n2;
			break;
			case '*':
				$n2 = $n1 * $n2;
			break;
			case '/':
				$n2 = $n1 / $n2;
			break;
		}
	}
	return $n2;
}
调用方法:
$a = '1-7+8*(3+9)';
echo maths($a);

如有错误及bug欢迎指正!

你可能感兴趣的:(php)