Parsica, PHP Parser Combinators, is the easiest way to build robust parsers in PHP. A parser is a function that takes some unstructured input (like a string) and turns it into structured output, that’s easier to work with. This output could be as simple as a slightly better structured string, or an array, an object, up to a complete abstract syntax tree. You can then use this data structure for subsequent processing.

Parsica helps you build your own parsers, in a concise, declarative way. Behind the scenes it takes care of things like error handling, so you can focus on the parser itself.

There are many ways to build a parser for your own use case, ranging from formal grammars that get compiled into a parser, to regular expressions, to writing a parser entirely from scratch. They all have their own tradeoffs and limitations.

One of the great benefits of the parser combinator style is that, once you get the hang of it, they’re generally easier to write, understand, and maintain. You start from building blocks, such as digitChar(), which returns a function that parses a single digit.

<?php 
$parser = digitChar();
$input = "1. Write Docs";
$result = $parser->tryString($input);
$output = $result->output();
assert($output === "1");
assert(is_string($output));

Parser Combinators are functions (or methods) that combine parsers into new parsers. Instead of writing one big parser, we can now write smaller parsers and cleverly compose them into larger parsers.

Parsica is written by Mathias Verraes and released under an MIT license. More information at https://parsica.verraes.net/

LEAVE A REPLY

Please enter your comment!
Please enter your name here