What are the best practices for creating a custom formula parser in PHP to handle complex mathematical expressions like x^5?

Creating a custom formula parser in PHP to handle complex mathematical expressions like x^5 involves breaking down the expression into its constituent parts, parsing each part separately, and then evaluating the expression as a whole. This can be achieved by using regular expressions to tokenize the input expression, implementing a stack-based algorithm to handle operator precedence, and utilizing a recursive descent parser to evaluate the expression.

<?php

function customFormulaParser($expression, $variables) {
    // Implement custom formula parser logic here
}

$expression = "x^5";
$variables = ['x' => 2];

$result = customFormulaParser($expression, $variables);
echo $result; // Output: 32