expression.php
2.0.0
当您想评估不受信任来源的数学或布尔表达式时,请使用表达式类别。您可以定义存储在对象中的变量和函数。
*
/
-
+
%
, ^
和**
&&
, ||
, 和!
>
<
==
!=
<=
>=
===
和!==
pi
和e
常数=~
>>
<<
composer require jcubic/expression
<?
require_once ( __DIR__ . " /vendor/autoload.php " );
use jcubic Expression ;
$ e = new Expression ();
// basic evaluation:
$ result = $ e -> evaluate ( ' 2+2 ' );
// supports: order of operation; parentheses; negation; built-in functions
$ result = $ e -> evaluate ( ' -8(5/2)^2*(1-sqrt(4))-8 ' );
// support of booleans
$ result = $ e -> evaluate ( ' 10 < 20 || 20 > 30 && 10 == 10 ' );
// support for strings and match (regexes can be like in php or like in javascript)
$ result = $ e -> evaluate ( ' "Foo,Bar" =~ /^([fo]+),(bar)$/i ' );
// previous call will create $0 for whole match match and $1,$2 for groups
$ result = $ e -> evaluate ( ' $2 ' );
// create your own variables
$ e -> evaluate ( ' a = e^(ln(pi)) ' );
// or functions
$ e -> evaluate ( ' f(x,y) = x^2 + y^2 - 2x*y + 1 ' );
// and then use them
$ result = $ e -> evaluate ( ' 3*f(42,a) ' );
// create external functions
$ e -> functions [ ' foo ' ] = function () {
return " foo " ;
};
// and use them
$ result = $ e -> evaluate ( ' foo() ' );
$e->evalute($expr)
评估表达式并返回结果。如果发生错误,请打印警告并返回false。如果$ expr是函数分配,则成功返回。
$e->e($expr)
$ e-> evaliate()的同义词。
$e->vars()
返回所有用户定义的变量和值的关联数组。
$e->funcs()
返回所有用户定义功能的数组。
$e->suppress_errors
评估表达式时,设置为true以关闭警告
$e->last_error
如果上次评估失败,则包含一个描述错误的字符串。 (当抑制时有用时)。
$e->functions
包含外部定义的函数的关联阵列。
$e->variables
合作数组包含用户和外部定义的变量。
这个项目始于叉子。原始代码由Miles Kaufmann创建,并在phpclasses.org上发布。我已经在原始代码中添加了许多功能和错误修复,但是随后确定该代码确实很难修改以添加新功能并修复错误。因此,我决定使用PEG Parser Generator从头开始重写所有内容。
原始代码仍然可以作为Packagist上的1.0版和您可以在Legacy Branch中找到的源代码提供。
版权(C)2024 Jakub T. Jankiewicz
根据MIT许可发布