|
Posted by Sjoerd on 01/20/06 14:29
There are several options:
1. Check the user input to only contain number, operators and
parenthesis and then supply it to eval. This would be safer than using
eval without checking, but it may still be insecure and it is not the
right option. If you need to accept variables and functions in the
expression, making this secure becomes close to impossible.
2. You may parse the expression and compute the result using PHP code.
This is a better option, but may not be worth the time it takes to
write a parser.
I tried searching the web for a math expression parser, but I did not
found one. I have written something to get you started:
http://svn.linuxonly.nl/filedetails.php?repname=svn.linuxonly.nl&path=%2Fphp%2Fcalculator%2Fcalculator.php
It is not complete. It does not check parenthesis and does not give
precendence to * over + (for example). It converts the expression to
Reverse Polish notation and than computes it.
If you want to extend my file, you may find
http://en.wikipedia.org/wiki/Reverse_Polish_Notation interesting.
Please send any new version to me.
Good luck.
Navigation:
[Reply to this message]
|