Skip to content
PHP Logo

How can input validation be implemented to ensure that only valid mathematical expressions are processed in PHP?

Input validation can be implemented in PHP to ensure that only valid mathematical expressions are processed by using regular expressions to check for valid characters and structure. This can help prevent injection attacks and ensure that the input is safe to evaluate as a mathematical expression.

php
$input = $_POST['expression'];

// Validate input using regular expression
if (preg_match('/^[0-9\+\-\*\/\(\)\s]+$/', $input)) {
    // Input is a valid mathematical expression, proceed with evaluation
    $result = eval("return $input;");
    echo "Result: $result";
} else {
    // Input is not a valid mathematical expression
    echo "Invalid input. Please enter a valid mathematical expression.";
}