What best practices should be followed when allowing users to input mathematical expressions in a web form?

When allowing users to input mathematical expressions in a web form, it is important to sanitize and validate the input to prevent any security vulnerabilities or errors in calculations. One way to achieve this is by using a server-side validation script to evaluate the mathematical expression and ensure it is safe to process. Additionally, providing clear instructions and error messages for invalid inputs can help improve the user experience.

<?php
// Get the mathematical expression input from the form
$math_expression = $_POST['math_expression'];

// Sanitize the input by removing any non-numeric or non-operator characters
$clean_expression = preg_replace("/[^0-9+\-*\/\(\) ]/", "", $math_expression);

// Validate the expression to ensure it is safe to evaluate
if (preg_match("/^[0-9+\-*\/\(\) ]+$/", $clean_expression)) {
    // Evaluate the mathematical expression
    $result = eval("return $clean_expression;");
    echo "Result: " . $result;
} else {
    echo "Invalid mathematical expression. Please try again.";
}
?>