note 114272 deleted from function.eval by googleguy
| From: | googleguy@php.net | Date: | Fri, 24 Feb 2017 21:12:43 +0000 |
| Subject: | note 114272 deleted from function.eval by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208832@lists.php.net to get a copy of this message | ||
Note Submitter: sooncj
----
Modified version of bohwaz's answer: with negative number support and removes the requirement
of properly grouped (bracketed) expressions.
<?php
function calc($equation)
{
// Remove whitespaces
$equation = preg_replace('/\s+/', '', $equation);
echo "$equation\n";
$number = '(?:-?\d+(?:[,.]\d+)?|pi|Ï)'; // What is a number
$functions =
'(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)';
// Allowed PHP functions
$operators = '[+\/*\^%-]'; // Allowed math operators
$regexp =
'/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/';
// Final regexp, heavily using recursive patterns
if (preg_match($regexp, $equation))
{
$equation = preg_replace('!pi|Ï!', 'pi()', $equation); // Replace pi with
pi function
echo "$equation\n";
eval('$result = '.$equation.';');
}
else
{
$result = false;
}
return $result;
}
?>