开发者

PHP: Calculate a math function f(x) in a string

开发者 https://www.devze.com 2023-01-25 14:33 出处:网络
Is it possible to calculate a math function f(x) that in a string. Something like this: $function = \'2x+3\';

Is it possible to calculate a math function f(x) that in a string. Something like this:

$function = '2x+3';
$x = 4;
math开发者_StackOverflow社区_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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号