PHPackages                             maximebf/parsec - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. maximebf/parsec

AbandonedArchivedLibrary[Parsing &amp; Serialization](/categories/parsing)

maximebf/parsec
===============

Contextual parser library for PHP5.3

1.0.0(13y ago)2412.6k1[2 issues](https://github.com/maximebf/parsec/issues)MITPHPPHP &gt;=5.3.0

Since Aug 18Pushed 8y ago3 watchersCompare

[ Source](https://github.com/maximebf/parsec)[ Packagist](https://packagist.org/packages/maximebf/parsec)[ Docs](https://github.com/maximebf/parsec)[ RSS](/packages/maximebf-parsec/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (2)Used By (0)

Parsec
======

[](#parsec)

**Contextual text parser in PHP 5.3.**

[![Build Status](https://camo.githubusercontent.com/68c0d3bcd0f574dc361f044d4bd9a2aa221ef8679ff84ea79209fa8e57e76131/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f6d6178696d6562662f7061727365632e706e67)](http://travis-ci.org/maximebf/parsec)

Parsec is a really simple parser toolkit which can be used to create small [DSL](http://en.wikipedia.org/wiki/Domain-specific_language) in PHP.

Installation
------------

[](#installation)

The easiest way to install Parsec is using [Composer](https://github.com/composer/composer)with the following requirement:

```
{
    "require": {
        "maximebf/parsec": ">=1.0.0"
    }
}

```

Alternatively, you can [download the archive](https://github.com/maximebf/parsec/zipball/master)and add the src/ folder to PHP's include path:

```
set_include_path('/path/to/src' . PATH_SEPARATOR . get_include_path());

```

Parsec does not provide an autoloader but follows the [PSR-0 convention](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md).
You can use the following snippet to autoload Parsec classes:

```
spl_autoload_register(function($className) {
    if (substr($className, 0, 6) === 'Parsec') {
        $filename = str_replace('\\', DIRECTORY_SEPARATOR, trim($className, '\\')) . '.php';
        require_once $filename;
    }
});

```

Creating a lexer
----------------

[](#creating-a-lexer)

A string must be tokenized using a [lexer](http://en.wikipedia.org/wiki/Lexical_analysis) before being parsed. Lexers can be created using the `Parsec\Lexer` class. Tokens are defined as an associative array where keys are their name and values are a regular expression without the delimiting characters (forward slash, you'll need to escape characters).

```
$lexer = new Parsec\Lexer(array(
    'number' => '[0-9]+',
    'plus' => '\+',
    'minus' => '\-',
    'multi' => '\*',
    'div' => '\/',
    'bracketOpen' => '\(',
    'bracketClose' => '\)'
));
$tokens = $lexer->tokenize($string);

```

The result of the last line is an array with each token represented as an associative array with a 'token' key and a 'value' key. Unmatched strings are added to the array as well.

Creating a parser
-----------------

[](#creating-a-parser)

As most of parsers are meant to parse text, Parsec includes the `Parsec\StringParser` class. It already provides all the needed code to loop through the token array. Parsers can also be created from the ground up using `Parsec\AbstractParser`.

In the following example, `StringParser` will be used. Configuring a lexer and a context factory can be done by overriding the constructor. A context factory defines in which namespaces to find context classes. It is also possible to override the parse method to specify the context in which to start.

```
class ArithParser extends Parsec\StringParser
{
    public function __construct()
    {
        $factory = new Parsec\ContextFactory(array('\\'));
        $lexer = new Parsec\Lexer(array(
            'number' => '[0-9]+',
            'plus' => '\+',
            'minus' => '\-',
            'multi' => '\*',
            'div' => '\/',
            'bracketOpen' => '\(',
            'bracketClose' => '\)'
        ));
        parent::__construct($lexer, $factory);
    }

    public function parse($string)
    {
        return parent::parse($string, 'Expression');
    }
}

```

Creating contexts
-----------------

[](#creating-contexts)

Contexts are classes which inherit from Context and which will do something with the tokens. One method must be created for each tokens that need to be handled. These methods must start by "token" followed by the capitalized token name. They will receive the value of the token.

It is possible to enter a new context using the `enterContext()` method or exit the current one using `exitContext()`. This last method takes one argument which will be returned as the result of the context.

The "eos" token (End Of String) will be automatically appended to the tokens array. Unmatched string can be caught using the "text" token.

```
class Expression extends Parsec\Context
{
    protected $number;

    public function tokenNumber($value)
    {
        $this->number = $value;
    }

    public function tokenPlus()
    {
        $this->exitContext($this->number + $this->enterContext('Expression'));
    }

    public function tokenMinus()
    {
        $this->exitContext($this->number - $this->enterContext('Expression'));
    }

    public function tokenMulti()
    {
        $this->exitContext($this->number * $this->enterContext('Expression'));
    }

    public function tokenDiv()
    {
        $this->exitContext($this->number / $this->enterContext('Expression'));
    }

    public function tokenBracketOpen()
    {
        if ($this->number === null) {
            $this->number = 1;
        }
        $this->exitContext($this->number * $this->enterContext('Expression'));
    }

    public function tokenBracketClose()
    {
        $this->exitContext($this->number);
    }

    public function tokenEos($text)
    {
        $this->exitContext($this->number);
    }
}

```

Using
-----

[](#using)

```
$parser = new ArithParser();
printf("3 + 4 = %s\n", $parser->parse('3 + 4'));
printf("6 * (2 / 3) = %s\n", $parser->parse('6 * (2 / 3)'));

```

###  Health Score

33

—

LowBetter than 77% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity34

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

4963d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9f4245e71c37880b2993d787844f7ea169f81fe7e0a760e24354e5e8d973c5fb?d=identicon)[maximebf](/maintainers/maximebf)

---

Top Contributors

[![maximebf](https://avatars.githubusercontent.com/u/305740?v=4)](https://github.com/maximebf "maximebf (21 commits)")

---

Tags

parserlexercontextual

### Embed Badge

![Health badge](/badges/maximebf-parsec/health.svg)

```
[![Health](https://phpackages.com/badges/maximebf-parsec/health.svg)](https://phpackages.com/packages/maximebf-parsec)
```

###  Alternatives

[doctrine/lexer

PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.

11.2k896.2M97](/packages/doctrine-lexer)[cerbero/json-parser

Zero-dependencies pull parser to read large JSON from any source in a memory-efficient way.

804445.9k5](/packages/cerbero-json-parser)[creof/geo-parser

Parser for geography coordinate strings

634.3M15](/packages/creof-geo-parser)[creof/wkt-parser

Parser for well-known text (WKT) object strings

554.8M16](/packages/creof-wkt-parser)[tmilos/lexer

Lexical analyzer with individual token definition with regular expressions

211.7M2](/packages/tmilos-lexer)[yosymfony/parser-utils

Parser utilities

201.4M2](/packages/yosymfony-parser-utils)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
