php实现混合四则运算函数

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

/*******************四则运算计算器********************/
function maths($exp){
	$arr_exp = [];
	for($i=0;$i<strlen($exp);$i++){
		if($exp[$i]=='+' || $exp[$i]=='-' || $exp[$i]=='*' || $exp[$i]=='/' || $exp[$i]=='(' || $exp[$i]==')'){
			$arr_exp[] = $exp[$i];
		}else{
			if(end($arr_exp)=='+' || end($arr_exp)=='-' || end($arr_exp)=='*' || end($arr_exp)=='/' || end($arr_exp)=='(' || end($arr_exp)==')' || end($arr_exp)==''){
				$arr_exp[] = $exp[$i];
			}else{
				$arr_exp[key($arr_exp)] = end($arr_exp).$exp[$i];
			}
		}
	}	
	$result = calculator( array_reverse($arr_exp) );
	return $result;
}
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欢迎指正!

其余

作为码农,推荐几个自己亲身使用过的云服务器平台给大家,感觉还不错有需要小伙伴自行查看:
1.阿里云:https://www.aliyun.com/?source=5176.11533457&userCode=mszy7nm5
2.腾讯云服务器:https://curl.qcloud.com/jgwhoTBS
另外偷偷透露一下,腾讯云的轻量服务器作简直不要太好,便宜、稳定、速度还够快。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值