note 114921 added to function.eval

From: Date: Sun, 27 Apr 2014 10:04:40 +0000
Subject: note 114921 added to function.eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-199338@lists.php.net to get a copy of this message
Sorry, some corrections to my note... I've: * removed the minus sign -? at the beginning and readded the |pi|π at the end like in previous examples; * added some math functions; * added the , in the operators: now it is possible to calculate pow(1,3) or rand(1,10); * changed 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+)?|pi|π)'; // What is a number $functions = '(?:sinh?|cosh?|tanh?|acosh?|asinh?|atanh?|exp|log(10)?|deg2rad|rad2deg |sqrt|pow|abs|intval|ceil|floor|round|(mt_)?rand|gmp_fact)'; // 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: 72.52.91.14 Probable Submitter: 5.96.92.210 ---- Manual Page -- http://php.net/manual/en/function.eval.php Edit -- https://master.php.net/note/edit/114921 Del: integrated -- https://master.php.net/note/delete/114921/integrated Del: useless -- https://master.php.net/note/delete/114921/useless Del: bad code -- https://master.php.net/note/delete/114921/bad+code Del: spam -- https://master.php.net/note/delete/114921/spam Del: non-english -- https://master.php.net/note/delete/114921/non-english Del: in docs -- https://master.php.net/note/delete/114921/in+docs Del: other reasons-- https://master.php.net/note/delete/114921 Reject -- https://master.php.net/note/reject/114921 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199338) next »