PHP code example of rafaelnajera / matcher

1. Go to this page and download the library: Download rafaelnajera/matcher 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/ */

    

rafaelnajera / matcher example snippets


$pattern = (new Pattern())->withTokenSeries(['a', 'b'])
           ->withAddedPatternZeroOrMore((new Pattern())->withTokenSeries(['c', 'd']))
           ->withTokenSeries(['e']);

$matcher = new Matcher($pattern);
$r = $matcher->match('a');
$r = $matcher->match('b');
...

$m = $matcher->matchFound();

$matcher->reset();

$r = $matcher->matchArray(['a', 'b', 'c']);

$r = $matcher->matchArray(['a', 'b', 'c'], false);

$pattern = (new Pattern())->withTokenSeries(['a', 'b', 'c'])
   ->withCallback( 
    function ($m) {
        return implode($m);
    }
);

$matcher = new Matcher($pattern);
$matcher->matchArray(['a', 'b', 'c', 'e']);

$matcher->matchFound();  // true
$matcher->matched;  // 'abc'

$subPattern = (new Pattern())->withTokenSeries(['c', 'd'])
     ->withCallback( function($m) { ... });

$pattern = (new Pattern())->withTokenSeries(['a', 'b'])
        ->withAddedPatternZeroOrMore($subPattern)
        ->withTokenSeries(['e']);

$matcher = new Matcher($pattern);

$pattern = (new Pattern())->withTokenSeries(['a', 'b', Token::EOF]);
        
$matcher = new Matcher($pattern);
        
$matcher->matchArray(['a', 'b']);  // no match
$matcher->matchArray(['a', 'b', Token::EOF]); // match found!

$pmatcher = new ParallelMatcher(
    [
        (new Pattern())->withTokenSeries(['(', 'a', ')']),
        (new Pattern())->withTokenSeries(['(', 'b', ')']),
        (new Pattern())->withTokenSeries(['(', 'c', ')'])
    ]
);

$r = $pmatcher->match('('); // false if the input token does not match any pattern
...
 
$result = $pmatcher->matchArray(['(', 'c', ')', '(', 'c', ')']); // true
$pmatcher->numMatches();  // 2

$result = $pmatcher->matchArray(['(', 'a', ')', '(', 'x', ')']); // false
$pmatcher->numMatches();  // 1