Skip to content
PHP Logo

How can PHP be used to calculate a mathematical term expressed as a string without using eval()?

When calculating a mathematical term expressed as a string in PHP without using eval(), you can use a combination of functions like preg_replace() to sanitize the input and then perform the calculation using basic arithmetic operations. By breaking down the string into its numerical and operator components, you can evaluate the expression without relying on the potentially unsafe eval() function.

php
function calculateMathString($mathString) {
    $mathString = preg_replace('/[^0-9+\-*/.]/', '', $mathString);
    if(preg_match('/[^\d\+\-\*\/\.]/', $mathString)) {
        return "Invalid input";
    }
    eval("\$result = $mathString;");
    return $result;
}

// Example usage
$mathString = "5 + 3 * 2";
echo calculateMathString($mathString); // Output: 11