khumbal / php-formula-interpreter

PHP 表达式解释器

v1.1.1 2024-09-02 20:50 UTC

This package is auto-updated.

Last update: 2024-10-02 21:08:31 UTC


README

PHP 表达式解释器

为什么选择这个库?

有些用户可能需要执行简单的计算,并尽可能多地修改它。在使用库之前,你可以使用 eval 函数。但这种方法有两个主要缺点:

  • 安全性。PHP 脚本是通过 eval 函数进行评估的。PHP 是一种非常强大的语言,可能对于用户来说过于强大,尤其是当用户想要注入恶意代码时。

  • 复杂性。PHP 对于不熟悉编程语言的人来说也很复杂。解析类似 Excel 的公式可能更好。

安装

使用 Composer 安装

composer require khumbal/php-formula-interpreter

它是如何工作的?

首先,创建一个 FormulaInterpreter\Compiler 的实例

$compiler = new FormulaInterpreter\Compiler();

然后使用 compile() 方法解析你想解释的表达式。它将返回一个 FormulaInterpreter\Executable 的实例

$executable = $compiler->compile('2 + 2');

最后,从可执行文件运行公式

$result = $executable->run();
// $result equals 4

使用运算符

运算符乘法 (*) 和除法 () 首先进行评估,然后是加法 (+) 和减法 (-)

你可以通过使用括号来强制表达式的优先级,如下所示

'2 * (3 + 2)'

你可以使用任意数量的括号。

'2 * (2 * (3 + 2 * (3 + 2)) + 2)'

比较运算符

支持的比较运算符有 =!=<>>=><= 和 '<'。

'1 = 1' //true
'1 != 1' //false
'1 != 2' //true
'1 < 2' //true

布尔运算符

支持的布尔运算符有 ANDOR

'(4 > 0) AND (3 > 2)' //true
'(4 > 0) AND (3 < 2)' //false
'(4 > 0) OR (3 < 2)' //true
'(4 < 0) AND (3 < 2)' //false

未来的运算符

将来将通过函数实现其他运算符,如取模、幂等。

使用变量

变量只是公式中的一个词,如下所示

'price * rate / 100'

在执行公式之前,请确保在一个数组中注入所有所需的变量

$variables = [
   'price' => 40.2,
   'rate' => 12.8
];

$executable->run($variables);

变量现在支持点 . 作为名称。

$variables = [
   'user.name' => 'John Doe'
   'user.age' => '23'
];

$executable->run($variables);

字符串支持

变量可以包含字符串。使用双引号 (") 来表示字符串。

'a = "Hello world"'

使用函数

以下是一个使用函数的表达式示例

   'cos(0)'

可用函数:pipowcossinsqrtmodulo

你可以嵌入任意数量的函数

   'pow(sqrt(4), 2)'

自定义函数

现在,如果需要添加更多变量,可以在编译之前添加函数。

$compiler = new Compiler();
$compiler->registerFunction('foobar', function ($a, $b) {
    return $a + $b;
});
$executable = $compiler->compile("foobar(foo, bar)");
$params = [
    'foo' => 1,
    'bar' => 2
];
$executable->run($params);

列出参数

你可以获取一个必须提供给 run() 方法才能运行可执行文件的变量列表

$executable = $compiler->compile('foo + bar');

print_r($executable->getParameters());

这将输出

    Array
    (
        [0] => foo
        [0] => bar
    )