PHP code example of ozhantr / ebnf

1. Go to this page and download the library: Download ozhantr/ebnf library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ozhantr / ebnf example snippets




declare(strict_types=1);

use Ozhantr\Ebnf\Lexer\Lexer;
use Ozhantr\Ebnf\Parser\Parser;

$grammar = 'digit = /^[0-9]/ ; number = digit , { digit } ;';

$tokens = (new Lexer($grammar))->tokenize();
$ast = (new Parser($tokens))->parse();

$grammar = 'identifier = /^[a-z_][a-z0-9_]*/ ;';



declare(strict_types=1);

use Ozhantr\Ebnf\Lexer\Lexer;
use Ozhantr\Ebnf\Parser\Parser;

$grammar = file_get_contents('path/to/grammar.ebnf');

if ($grammar === false) {
    throw new RuntimeException('Could not read grammar file.');
}

$ast = (new Parser((new Lexer($grammar))->tokenize()))->parse();



declare(strict_types=1);

use Ozhantr\Ebnf\Lexer\Lexer;
use Ozhantr\Ebnf\Parser\Parser;
use Ozhantr\Ebnf\Runtime\GrammarRuntime;

$grammar = 'number = /^[0-9]+/ ;';
$ast = (new Parser((new Lexer($grammar))->tokenize()))->parse();

$runtime = new GrammarRuntime($ast);
$result = $runtime->match('number', '12345');



declare(strict_types=1);

use Ozhantr\Ebnf\Analyzer\GrammarAnalyzer;
use Ozhantr\Ebnf\Lexer\Lexer;
use Ozhantr\Ebnf\Parser\Parser;

$grammar = 'start = missing ;';
$ast = (new Parser((new Lexer($grammar))->tokenize()))->parse();

$analysis = (new GrammarAnalyzer())->analyze($ast);
bash
composer install
php examples/basic.php
bash
php examples/parse-file.php
php examples/parse-file.php examples/grammars/calculator.ebnf
php examples/pretty-print.php
php examples/runtime-validate.php
php examples/runtime-validate.php 'status:open priority:high "payment bug"'
php examples/runtime-validate.php $'status:open\npriority:'
php examples/analyze-grammar.php
php examples/showcase.php