PHP:计算字符串中的数学函数f(x) [英] PHP: Calculate a math function f(x) in a string
本文介绍了PHP:计算字符串中的数学函数f(x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以计算一个字符串中的数学函数f(x)。像这样:
$ function ='2x + 3';
$ x = 4;
math_function($ function,$ x); // Shoud产生11
我无法在PHP.net上找到这样的任务库,或者与谷歌,但我不认为我是第一个想要这个?
解决方案
我对这个问题的标准答案每当它会出现:
不要使用eval(特别是如果公式包含用户输入)或者通过编写自己的公式分析器重新发明轮子。
查看 evalMath 类。它应该在安全的沙箱中完成你想要的任何事情。
Is it possible to calculate a math function f(x) that in a string. Something like this:
$function = '2x+3';
$x = 4;
math_function($function, $x); //Shoud produce 11
I can't find a library for tasks like this on PHP.net or with Google, but I don't think I am the first one that wants this?
解决方案
My standard answer to this question whenever it crops up:
Don't use eval (especially if the formula contains user input) or reinvent the wheel by writing your own formula parser.
Take a look at the evalMath class on PHPClasses. It should do everything that you want in a nice safe sandbox.
这篇关于PHP:计算字符串中的数学函数f(x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文