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許可發布