wouterj/peg

PHP 的 PEG 解析器

dev-master 2016-08-10 18:26 UTC

This package is auto-updated.

Last update: 2024-09-10 04:04:53 UTC


README

PEG 是用 PHP 编写的通用 PEG 解析器。这个解析器允许您使用解析表达式语法来编写解析器。

安装

使用 Composer 安装 PEG

$ composer require wouterj/peg

使用

使用 Grammar 类通过创建 Definition 实例来指定解析表达式语法

use WouterJ\Peg\Grammar;
use WouterJ\Peg\Definition;

// specifies that Float is the main definition
$grammar = new Grammar('Float', [
    // matches any Digits (next definition), followed by a . (dot) and any Digits
    new Definition('Float', ['sequence', [
        ['identifier', 'Digits'],
        ['literal', '.'],
        ['identifier', 'Digits'],
    ]]),

    // matches any Digit (next definition) one or more times
    new Definition('Digits', ['repeat', ['identifier', 'Digit'], 1]),

    // matches 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9
    new Definition('Digit', ['characterClass', '0-9']),
]);

使用 Grammar#parse() 来使用此语法解析输入字符串。返回值是匹配的字符串部分,或者当没有匹配时返回 null

// ...

echo $grammar->parse('1.2'); // 1.2
echo $grammar->parse('1039.50'); // 1039.50
echo $grammar->parse('abc'); // NULL

// please note that it doesn't have to match the full string
echo $grammar->parse('1.2a'); // 1.2

使用 PEG 语法

当然,使用数组定义语法真的很丑。这就是为什么 PEG 附带了一个 PegGrammar 解析器,它能够解析 PEG 语法。它返回一个使用解析的语法即可使用的语法实例。

use WouterJ\Peg\PegGrammar;

$pegGrammar = new PegGrammar();

// our float parser (equal to the previous one)
$grammar = $pegGrammar->parse(<<<EOG
Float  <- Digits '.' Digits
Digits <- Digit+
Digit  <- [0-9]
EOG
);

$grammar->parse('1039.50'); // 1039.50

有关 PEG 语法的更多信息,请参阅 Bryan Ford 的 Parsing Expression Grammars: A Recognition-Based Syntactic Foundation

许可证

该项目在 BSD-3 条款许可证下发布。有关完整的版权和许可证信息,请查看与源代码一起分发的 LICENSE 文件。

贡献

无论是参考资料、在线点赞、错误报告还是功能建议,所有贡献都欢迎。主要项目位于 GitHub