mossadal/math-parser
Safe PHP math expression parser/evaluator that builds an AST from user formulas. Supports arithmetic, variables, and elementary functions, plus interpreters for evaluation, symbolic differentiation, and LaTeX pretty-printing; customizable lexer/parser with StdMathParser.
eval().StdMathParser configuration). Mitigate with regex validation and input sanitization.2x vs. 2*x) may require explicit handling in validation.gmp) for financial/scientific use cases.['sin', 'log', 'sqrt']) be enforced?1/0) or type mismatches be handled? Custom exceptions or graceful degradation (e.g., return null with an error message)?myCustomFunc(x)) required? The package supports this but may need wrapper logic for integration.MathExpressionController).MathExpressionService) for reusability.MathExpressionEvaluated) for analytics or logging."2*x + sin(y)" with x=3, y=0).\\frac{2x + \\sin(y)}{1})."exp(2*x) - x*y").composer.json:
"require": {
"mossadal/math-parser": "^1.0"
}
$parser = new \Mossadal\MathParser\StdMathParser([
'functions' => ['sin', 'cos', 'log', 'sqrt'],
'variables' => ['x', 'y', 'z'] // Optional: restrict variables
]);
class MathExpressionService {
public function evaluate(string $expression, array $variables): float {
$parser = new StdMathParser();
$ast = $parser->parse($expression);
$evaluator = new \MathParser\Interpreting\Evaluator();
$evaluator->setVariables($variables);
return $ast->accept($evaluator);
}
}
public function rules() {
return [
'expression' => [
'required',
'regex:/^[a-zA-Z0-9+\-*\/^().\s]+$/', // Basic math syntax
'max:1000' // Prevent excessively long expressions
]
];
}
public function withValidator($validator) {
$validator->addRules([
'expression' => ['custom', function ($attribute, $value, $fail) {
$allowedFunctions = ['sin', 'cos', 'log', 'sqrt'];
preg_match_all('/\b([a-zA-Z]+)\s*\()/',$value, $matches);
$foundFunctions = array_unique($matches[1]);
$invalidFunctions = array_diff($foundFunctions, $allowedFunctions);
if (!empty($invalidFunctions)) {
$fail("Function(s) {$invalidFunctions[0]} not allowed.");
}
}]
]);
}
$cacheKey = 'math_ast:' . md5($expression);
$ast = cache()->remember($cacheKey, now()->addHours(1), function () use ($parser, $expression) {
return $parser->parse($expression);
});
$latexGenerator = new \MathParser\Interpreting\LatexGenerator();
$latex = $ast->accept($latexGenerator);
return response()->json(['latex' => $latex]);
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<div>{{ $latex }}</div>
How can I help you explore Laravel packages today?