tacoberu / bnf
构建类似BNF解析器的框架。
v1.2.0
2023-05-02 21:09 UTC
Requires
- php: >=5.3.3
Requires (Dev)
- php: >=7.4
- phpstan/phpstan: *
- phpunit/phpunit: ^9.0
- tracy/tracy: ^2.0
This package is auto-updated.
Last update: 2024-08-31 00:32:16 UTC
README
这是一个类似BNF解析器的PHP实现。
安装
推荐通过Composer进行安装
composer require tacoberu/bnf
使用
require __dir__ . '/vendor/autoload.php'; use Taco\BNF\Parser; use Taco\BNF\Combinators\Pattern; use Taco\BNF\Combinators\Whitechars; $parser = new Parser([ new Whitechars(Null, False), new Pattern('element', ['~[^\n]+~']), ]); $tree = $parser->parse(' -brand-name = Foo 3000 welcome = Welcome, {$name}, to {-brand-name}! '); print_r($tree); /* array ( [0] => Taco\BNF\Token ( [type] => Taco\BNF\Combinators\Pattern (...) [content] => "-brand-name = Foo 3000" [start] => 1 [end] => 23 ) [0] => Taco\BNF\Token ( [type] => Taco\BNF\Combinators\Pattern (...) [content] => "welcome = Welcome, {$name}, to {-brand-name}!" [start] => 24 [end] => 69 ) ) */
或更复杂
require __dir__ . '/vendor/autoload.php'; use Taco\BNF\Parser; use Taco\BNF\Combinators\Pattern; use Taco\BNF\Combinators\Whitechars; $parser = new Parser([ new Whitechars(Null, False), new Sequence('element', [ new Pattern('id', ['~[a-z\-]+~']), new Whitechars(Null, False), new Match(Null, ['='], False), new Whitechars(Null, False), new Pattern('element', ['~[^\n]+~']), ]), ]); $tree = $parser->parse(' -brand-name = Foo 3000 welcome = Welcome, {$name}, to {-brand-name}! '); print_r($tree); /* array ( [0] => Taco\BNF\Token ( [type] => Taco\BNF\Combinators\Sequence (...) [content] => array( [0] => Taco\BNF\Token ( [type] => Taco\BNF\Combinators\Pattern (...) [content] => "-brand-name" [start] => 1 [end] => 12 ) [1] => Taco\BNF\Token ( [type] => Taco\BNF\Combinators\Pattern (...) [content] => "Foo 3000" [start] => 15 [end] => 23 ) ) [start] => 1 [end] => 23 ) [0] => Taco\BNF\Token ( [type] => Taco\BNF\Combinators\Pattern (...) [content] => array( [0] => Taco\BNF\Token ( [type] => Taco\BNF\Combinators\Pattern (...) [content] => "welcome" [start] => 24 [end] => 31 ) [1] => Taco\BNF\Token ( [type] => Taco\BNF\Combinators\Pattern (...) [content] => "Welcome, {$name}, to {-brand-name}!" [start] => 34 [end] => 69 ) ) [start] => 24 [end] => 69 ) ) */
更多示例请参考 'tests/ExhibitionTest.php'。