`phpegjs` is a plugin for the PEG.js parser generator that enables the generation of parsers in PHP. Currently in beta version 1.0.0-beta7, it extends PEG.js to output PHP source code based on a given grammar, allowing developers to define complex parsing logic using PEG.js's syntax and then deploy the resulting parser in a PHP environment. This library acts as a crucial bridge for projects requiring robust parsing capabilities in PHP without manually writing lexical analyzers and parsers. It maintains compatibility with various PHP versions, offering options for namespace management and `mbstring` extension usage. The project is a fork of `php-pegjs` and focuses on providing a stable PHP target for PEG.js grammars, making it a key tool for language processing, DSL implementation, or complex data format parsing within PHP applications. Its release cadence is tied to its beta status, with updates reflecting progress towards a stable 1.0 release.
npm install phpegjsVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to use `phpegjs` with PEG.js to define a simple arithmetic grammar, generate the corresponding PHP parser code, and provides a conceptual example of how to instantiate and use the generated parser in a PHP application.
Ensure `mbstringAllowed` is `true` (default) if these features are required and the PHP `mbstring` extension is available, or avoid using these features if the extension is not installed.
For PHP 5.3 and later, set `phpegjs.parserNamespace` to define a namespace for the generated parser class. Only use `parserGlobalNamePrefix` if strict PHP 5.2 compatibility is a non-negotiable requirement.
Always set `cache: true` in the `pegjs.buildParser` options object, especially for complex or frequently used grammars, to enable memoization and optimize parsing performance.
If Unicode PCRE support is a concern or leads to unexpected behavior, pre-split the input string into an array of UTF-8 characters (e.g., `mb_str_split` in PHP) and pass this array directly to the parser's `parse` method instead of the raw string.
Either set `phpegjs.mbstringAllowed: true` in your `buildParser` options (requires PHP `mbstring` extension) or modify your grammar to remove the offending empty character class.
Review the input string for syntax errors based on your grammar. Utilize the `grammarLine`, `grammarColumn`, and `grammarOffset` properties of the `SyntaxError` exception for precise debugging location.
Ensure the generated PHP parser file is included using `require_once` or `include` at the beginning of your PHP script. Verify that the namespace used when instantiating the parser (e.g., `new MyNamespace\Parser()`) precisely matches the `parserNamespace` option configured in the `pegjs.buildParser` call.