2

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?

Woutb21
  • 247
  • 1
  • 2
  • 7

1 Answers1

3

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.

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • +1... Building a math formula parser is a great academic problem (since there are many well defined edge-cases which yield to a non-trivial solution). But in terms of a practical problem, it's not worth the effort since there are tools built for it... – ircmaxell Nov 18 '10 at 16:08
  • Wow, that was quick! Thank you very much. I didn't even know the existence of eval()! I will take a look at it. – Woutb21 Nov 18 '10 at 16:12
  • I'm confused: You say "Don't use eval" and then advice the use of a class that does exactly that. (Still perfectly valid answer that solves ops problem. So +1, even if the evalMath code makes me want to vomit ;) ) – edorian Nov 18 '10 at 16:16
  • 3
    @edorian - evalMath does NOT use eval! It uses Djikstra's shunting yard to parse the formula onto a stack, then processes operations using standard PHP methods in a controlled sandbox – Mark Baker Nov 18 '10 at 16:22
  • Glancing over the source one line read: eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval() --- And so i was confused. But you're right it _seems_ it doesn't use it for calulation. Thanks – edorian Nov 18 '10 at 16:44
  • 1
    @edorian - that instance could also be replaced with $r = call_user_func($fnn,$op1);$stack->push($r); which is cleaner than using eval(), and that's not dissimilar to what I did with my own math parser. – Mark Baker Nov 18 '10 at 17:12