tags:

views:

61

answers:

4

I'm writing a script that will allow a user to input a string that is a math statement, to then be evaluated. I however have hit a roadblock. I cannot figure out how, using preg_match, to dissallow statements that have variables in them.

Using this, $calc = create_function("", "return (" . $string . ");" ); $calc();, allows users to input a string that will be evaluated, but it crashes whenever something like echo 'foo'; is put in place of the variable $string.

I've seen this post, but it does not allow for math functions inside the string, such as $string = 'sin(45)';.

A: 

How complex of a math function do you need to allow? If you only need basic math, then you might be able to get away with only allowing whitespace + the characters 0123456789.+/-* or some such.

In general, however, using the language's eval-type capabilities to just do math is probably a bad idea.

Amber
A: 

For a stack-based parser implemented in PHP that uses Djikstra's shunting yard algorithm to convert infix to postfix notation, and with support for functions with varying number of arguments, you can look at the source for the PHPExcel calculation engine (and which does not use eval)

Also have a look at the responses to this question

Mark Baker
A: 

Something like:

^([\d\(\)\+\-*/ ,.]|sin\(|cos\(|sqrt\(|...)+$

would allow only numbers, brackets, math operations and provided math functions. But it won't check if provided expression is valid, so something like +++sin()))333((( would be still accepted.

serg
A: 

I wonder if this class would help you? Found that doing a search on Google for "php math expressions".

Inkspeak