在不使用eval()的情况下找到字符串方程式的答案 [英] Find answer to string equation without using eval()

查看:77
本文介绍了在不使用eval()的情况下找到字符串方程式的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种以字符串形式给出方程式并找到其数学答案的方法,最大的警告是我不能使用eval().

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?

推荐答案

数学表达式不是正则表达式.它们是无上下文.

Math expressions aren't regular. They're context-free.

您最好的选择是使用诸如调车场算法调车场算法.您只需要担心在PHP中实现该算法.您甚至可以在线找到它的PHP实现.

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.

这篇关于在不使用eval()的情况下找到字符串方程式的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆