在php中处理数学方程式 [英] Process mathematical equations in php
问题描述
允许用户输入他们喜欢的任何数学方程式(带有一个变量):
A user is allowed to enter any mathematical equation they like (with one variable):
x + 5
1 - x/2
(x/3) * (56/13)
这些作为字符串存储在数据库中.检索它们后,我需要用'x'代替一个数字并检查方程式的值.
These are stored as strings in the database. When they are retrieved I need to substitute 'x' for a number and check the value of the equation.
我该怎么办?
我当时正在考虑编写一个解析器来解构字符串并将其转换为方程式,但这听起来很昂贵且存在问题.另一种选择是让它们通过eval(但是如果可以帮助的话,我不是使用eval的忠实粉丝).
I was considering writing a parser to deconstruct the strings and turn them into equations, however this sounds expensive and problematic. The other option is to pass them through eval (but I'm not a great fan of using eval if I can help it).
有什么想法吗?
更新: 我还需要能够获得类似(x> 5)"的布尔值.使用evalMath不可能
UPDATE: I also need to be able to get the boolean value of something like "(x > 5)". This is not possible with evalMath
更新2: 我需要一秒钟将它们发射出很多.我一直在研究php中的eval,但无法获取它返回(5> 4)的布尔值,但是我注意到js会这样做...也许我应该研究node.js ...
UPDATE 2: I need to fire lots of these a second. I've been looking into eval in php but cant get it to return a boolean for (5 > 4) however I noticed js would do it... maybe I should investigate node.js...
更新3: 在尝试了一下node.js(并使其正常工作)后,我回过头来,开始在PHP中进行评估,请参见:
UPDATE 3: After having some fun trying out node.js (and getting it to work) I went back and got eval to work in PHP see: Can php eval return a boolean value?
因此,我将在eval上使用对用户输入非常非常严格的过滤器.
So I will go with eval with a very very hardcore filter on user input.
推荐答案
Eval不是邪恶的!!!!!
Eval is not Evil!!!!!
是的,如果您编写错误的代码,它可能会完全塞满您的系统-但是最新的PHP版本可以解析无效的表达式而不会导致整个脚本崩溃.还有许多其他方法可以通过编写错误的代码来公开系统.
Yes it can stuff your system up completely if you write bad code - but recent PHP versions can parse an invalid expression without crashing the whole script. And there are many other ways of exposing your system by writing bad code.
这只剩下代码注入攻击的可能性-通过对不是安全字符的Everythnig进行preg_replace即可轻松避免(例如0 .... 9,(,),+,-,*,/,^,.)
That just leaves the possiblity of code injection attacks - which can easily be avoided by doing a preg_replace on everythnig which is not a safe character (i.e. 0....9, (, ), +, -, *, /, ^, .)
这篇关于在php中处理数学方程式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!