|
Posted by Pedro Graca on 01/20/06 15:17
werner wrote:
> I don't want to use eval() in order to parse a user-supplied formula.
> What alternatives do I have? PHP has no standard functionality for
> tokenizing or parsing expressions in this regard.
Other than writing your own parser (or using one already done), I don't
think you have any alternatives.
> Here is a simple example: The user supplies the following formula in
> string format,
> "a = (6+10)/4",
> and the script needs to find out what the value of 'a' is.
>
> How can I go about it without using eval(), since using eval in this
> case could be very risky! (The user can supply *any* expression, as
> there is no function that can determine the meaning of the string as an
> expression).
Example using an already done parser (bc):
<?php
/* needs error checking */
$formula = 'a = (6+10)/4';
/* remove the left part of assignment */
$value = trim(substr($formula, strpos($formula, '=')+1));
$value = escapeshellarg($value);
$calculated = `echo $value | bc`; /* backticks! */
echo $calculated, "\n";
?>
tmp$ php foo.php
4
"bc" is "an arbitrary precision numeric processing language"
http://www.gnu.org/software/bc/bc.html
But, even so, I wouldn't pass input from the user directly to bc without
checking/validating it first (at least not until I've read thoroughly
bc's documentation).
--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Navigation:
[Reply to this message]
|