note 114272 added to function.eval
| From: | sooncj | Date: | Fri, 31 Jan 2014 15:51:04 +0000 |
| Subject: | note 114272 added to function.eval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198375@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 192.41.45.150
Probable Submitter: 207.237.150.246
----
Manual Page -- http://php.net/manual/en/function.eval.php
Edit -- https://master.php.net/note/edit/114272
Del: integrated -- https://master.php.net/note/delete/114272/integrated
Del: useless -- https://master.php.net/note/delete/114272/useless
Del: bad code -- https://master.php.net/note/delete/114272/bad+code
Del: spam -- https://master.php.net/note/delete/114272/spam
Del: non-english -- https://master.php.net/note/delete/114272/non-english
Del: in docs -- https://master.php.net/note/delete/114272/in+docs
Del: other reasons-- https://master.php.net/note/delete/114272
Reject -- https://master.php.net/note/reject/114272
Search -- https://master.php.net/manage/user-notes.php