views:

564

answers:

1

Just trying to figure out the proper and safer way to execute mathematic operation passed as string. In my scenario it is values fetched from image EXIF data. After little research I found two way of doing it.

first, using eval:

function calculator1($str){
    eval("\$str = $str;");
    return $str;
}

second, using create_function:

function calculator2($str)
{
    $fn = create_function("", "return ({$str});" );

    return $fn();
};

Both examples require string cleanup to avoid malicious code execution. Is there any other or shorter way of doing so?

+2  A: 
Byron Whitlock
Could you also add the code for this one which supports Reverse Polish Notation? http://www.phpclasses.org/browse/package/4078.html
jitter
thx for the RPN version
jitter