Skip to content

Instantly share code, notes, and snippets.

@bohwaz
Created February 4, 2012 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bohwaz/1740855 to your computer and use it in GitHub Desktop.
Save bohwaz/1740855 to your computer and use it in GitHub Desktop.
Allow user to compute maths in PHP
<?php
function mathEval($q)
{
$q = preg_replace('/\s+/', '', $q);
$number = '(?:\d+(?:[,.]\d+)?|pi|π)';
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)';
$operators = '[+\/*\^%-]';
$regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))*)+$/';
if (preg_match($regexp, $q))
{
$q = strtr($q, array(',' => '.', 'pi' => 'pi()', 'π' => 'pi()'));
eval('$ret = (float) '.$q.';');
return $ret;
}
return false;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment