What are the best practices for handling mathematical expressions with multiple operators in PHP, such as in the example "17/2+3-22+-2"?

When handling mathematical expressions with multiple operators in PHP, it is important to follow the correct order of operations (PEMDAS/BODMAS). One approach is to use the eval() function to evaluate the expression as a string. However, it is crucial to sanitize the input to prevent code injection vulnerabilities. Another approach is to use regular expressions to parse and evaluate the expression step by step.

<?php
// Mathematical expression with multiple operators
$expression = "17/2+3-22+-2";

// Sanitize the input to prevent code injection
$clean_expression = preg_replace('/[^0-9+\-\/\*]/', '', $expression);

// Evaluate the expression using eval()
eval('$result = ' . $clean_expression . ';');

echo "Result: " . $result;
?>