|
Posted by Umberto Salsi on 09/10/05 07:17
"tobimarq" <tobimarq@gmail.com> 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
[Back to original message]
|