# string to number conversion with mathematical interpretation

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
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...

## Re: string to number conversion with mathematical interpretation

On Unix you can evaluate the equation by spawning an instance of bc.

## Re: string to number conversion with mathematical interpretation

# \$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

## Re: string to number conversion with mathematical interpretation

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