note 114916 deleted from function.eval by googleguy
| From: | googleguy@php.net | Date: | Fri, 24 Feb 2017 21:11:38 +0000 |
| Subject: | note 114916 deleted from function.eval by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208824@lists.php.net to get a copy of this message | ||
Note Submitter: andrea at donboscoland dot it
----
Modified version of Daniele Mams's answer: I change the $number definition to accept scientific
notation like in:
http://stackoverflow.com/questions/638565/parsing-scientific-notation-sensibly
<?php
function calc($equation)
{
// Remove whitespaces
$equation = preg_replace('/\s+/', '', $equation);
echo "$equation\n";
$number = '(-?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)'; // What is a number
$functions =
'(?:abs|atan|ceil|cos|exp|gmp_fact|intval|log(10)?|rand|round|sin|sqrt|tan)'; // 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;
}
?>