434,668 Members | 1,477 Online + Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,668 IT Pros & Developers. It's quick & easy.

string to number conversion with mathematical interpretation

 P: n/a hi all, I wonder if the following is possible in php: I want php to 'interpret' a string that contains (a simple kind of) mathematical calculation, like \$var='25*3'; \$result= (int) \$var; //according to the php manual, \$result contains 25, //but I want the result at the end to contain: 75 Is there a php function or construct, that does this? ok, I know I could write a function that parses and splits the string \$var in the relevant parts, then calculating the result and give it back. In fact, that wouldn't even be complicated. But shouldn't it be somehow possible in a 'smarter' way? thank you for any comment... Sep 9 '05 #1
3 Replies

 P: n/a On Unix you can evaluate the equation by spawning an instance of bc. Sep 9 '05 #2

 P: n/a "tobimarq" wrote: hi all, I wonder if the following is possible in php: I want php to 'interpret' a string that contains (a simple kind of) mathematical calculation, like \$var='25*3'; \$result= (int) \$var; //according to the php manual, \$result contains 25, //but I want the result at the end to contain: 75 Is there a php function or construct, that does this? ok, I know I could write a function that parses and splits the string \$var in the relevant parts, then calculating the result and give it back. In fact, that wouldn't even be complicated. But shouldn't it be somehow possible in a 'smarter' way? thank you for any comment... # \$var must be an expression of the form # # int OP int OP ... OP int # # where int is a natural number (0, 1, 2, ...) and OP is one of the # aritmethic operators + - * / \$var='25*3'; if( ! ereg('^[0-9]+([-+*/][0-9]+)*\$', \$var) ){ echo \$var, ": invalid expression"; exit(1); } \$result = eval("return \$var;"); if( ! \$result ){ echo \$var, ": error evaluating the expression"; exit(1); } echo "\$var = \$result"; Ciao, ___ /_|_\ Umberto Salsi \/_\/ www.icosaedro.it Sep 10 '05 #3

 P: n/a wow! nice use of eval(), thanks a lot! Seems to work with non-integer-numbers as well (when changing the regex-parts [0-9] to [0-9.]) cu, Tobias Sep 10 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion. 