开发者

PHP preg_match Math Function

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 when开发者_如何学Cever 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)';.


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


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.


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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜