在php中处理数学方程 [英] Process mathematical equations in php

查看:28
本文介绍了在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(并让它工作)获得一些乐趣后,我回去让 eval 在 PHP 中工作,请参阅:php eval 可以返回一个布尔值吗?

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 is not Evil!!!!!!

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.

这就留下了代码注入攻击的可能性——这可以通过对所有不是安全字符(即 0....9、(、)、+、-、*、/)执行 preg_replace 来轻松避免, ^, .)

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屋!

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