不使用 eval() 查找字符串方程的答案
我需要一种方法来获取以字符串形式给出的方程并找到它的数学答案,最大的警告是我不能使用 eval()。
我知道方程只包含数字、四个数学运算符(即 * / + -)和括号,字符串中可能有也可能没有空格。这里有几个例子。
4 * 4
4+6/3
(3 / 2)*(4+8)
(4+8) * 2
我猜这必须使用某种正则表达式来完成?
I need a way of taking an equation given as a string and finding it's mathematical answer, the big caveat is that I can't use eval().
I know the equation will only ever contain numbers, the four mathematical operators (i.e. * / + -) and parentheses, it may or may not have spaces in the string. Here's a couple of examples.
4 * 4
4+6/3
(3 / 2)*(4+8)
(4+8) * 2
I'm guessing that it's going to have to be done with some kind of regex?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
数学表达式不规则。它们与上下文无关。
最好的选择是使用众所周知的数学解析算法来解析它们,例如调车场算法。您只需担心在 PHP 中实现该算法即可。您甚至可以在线找到它的 PHP 实现。
Math expressions aren't regular. They're context-free.
Your best bet is to parse them using well-known math parsing algorithms like the shunting yard algorithm. All you have to worry about is implementing the algorithm in PHP. You might even be able to find PHP implementations of it online.
以防万一有人对此感兴趣,这是我在 PHP 中提出的用于生成逆波兰表示法的算法
Just in case anybody's interested here is the algorithm I came up with in PHP for producing Reverse Polish Notation