How can regular expressions be utilized in PHP to achieve similar results as eval() without the associated risks?

Using regular expressions in PHP can help achieve similar results as eval() without the associated risks by allowing for pattern matching and manipulation of strings without executing potentially harmful code. By carefully crafting regular expressions, you can control the input and output of data, ensuring that only safe and expected values are processed.

// Example of using regular expressions in PHP to achieve similar results as eval() without the associated risks
$input = "5 * 10";
$pattern = '/^(\d+)\s*([\+\-\*\/])\s*(\d+)$/';

if (preg_match($pattern, $input, $matches)) {
    $num1 = (int)$matches[1];
    $operator = $matches[2];
    $num2 = (int)$matches[3];

    switch ($operator) {
        case '+':
            $result = $num1 + $num2;
            break;
        case '-':
            $result = $num1 - $num2;
            break;
        case '*':
            $result = $num1 * $num2;
            break;
        case '/':
            $result = $num1 / $num2;
            break;
        default:
            $result = "Invalid operator";
    }

    echo "Result: $result";
} else {
    echo "Invalid input format";
}