本文介绍了使用PHP解析数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目上,我需要做一个函数来解析这4个默认的数学运算(加法,减法,乘法,除法).如果该函数可以解析方括号之间的操作,那就太好了.

I am working on a project where I need to make a function that will parse the 4 default math operations (addition, subtraction, multiplication, division). It would be nice if the function could parse operations between brackets.

因此,必须要做的是该函数首先检查乘法和除法运算(在解析括号之间的所有运算(如果存在的话)之后应进行检查,并且该规则应适用于括号运算[最大的问题是括号可以包含括号]).完成所有乘法和除法运算后,应执行所有加法和减法运算.最终的数字应由函数返回.

So, a must is that the function first check for multiplication and division operations (should check for that after it parser all operations between brackets if they exist, and that rule should apply for bracket operations [the biggest problem is that the brackets can contain brackets]). After doing all multiplication and division operations, it should do all addition and subtraction operations. The final number should be returned by functions.

另一个不错的选择是RegExp字符串,该字符串将检查数学运算.

Another nice addition would be a RegExp string that will check for math operations.

提前谢谢!

推荐答案

这应该很安全:

function do_maths($expression) {
  eval('$o = ' . preg_replace('/[^0-9\+\-\*\/\(\)\.]/', '', $expression) . ';');
  return $o;
}

echo do_maths('1+1');

这篇关于使用PHP解析数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:59