PHPackages                             nicoswd/php-rule-parser - 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. nicoswd/php-rule-parser

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

nicoswd/php-rule-parser
=======================

Rule Engine - Rule Parser &amp; Evaluator

v0.8(7mo ago)13078.6k↓35.6%18[3 issues](https://github.com/nicoSWD/php-rule-parser/issues)7MITPHPPHP &gt;=8.4

Since Jul 22Pushed 7mo ago6 watchersCompare

[ Source](https://github.com/nicoSWD/php-rule-parser)[ Packagist](https://packagist.org/packages/nicoswd/php-rule-parser)[ Docs](https://github.com/nicoSWD/php-rule-parser)[ RSS](/packages/nicoswd-php-rule-parser/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (27)Used By (7)

PHP Rule Engine
---------------

[](#php-rule-engine)

[![Latest Stable Version](https://camo.githubusercontent.com/80a2e1bdd4a6cf888d7ca896305e238a4497e6abcebbffc151a884c86a394dcd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e69636f7377642f7068702d72756c652d7061727365722e737667)](https://packagist.org/packages/nicoswd/php-rule-parser)[![Total Downloads](https://camo.githubusercontent.com/822ca406d20daaaf7f7f723564990dc15ac3fd2b46e488d6397393241b76496c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e69636f7377642f7068702d72756c652d7061727365722e737667)](https://packagist.org/packages/nicoswd/php-rule-parser)[![Build status](https://camo.githubusercontent.com/d6770049cf0322de3cb745060ef4479407adbd6ef66d4aef3900c603c2aa9ef2/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e69636f5357442f7068702d72756c652d7061727365722f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/nicoSWD/php-rule-parser/?branch=master)[![Code Quality](https://camo.githubusercontent.com/334c7cbd65cb9d77b03af149a5c5a9426fd8d5cca6b993397a487161edd934f3/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6e69636f7377642f7068702d72756c652d7061727365722e7376673f623d6d6173746572)](https://scrutinizer-ci.com/g/nicoSWD/php-rule-parser/?branch=master)[![StyleCI](https://camo.githubusercontent.com/e4b078d34efa1a34b69470810366e86c0f4e58c03d0e0d3646a2ce3a8e1d7cea/68747470733a2f2f7374796c6563692e696f2f7265706f732f33393530333132362f736869656c643f6272616e63683d6d6173746572267374796c653d666c6174)](https://styleci.io/repos/39503126)

You're looking at a standalone PHP library to parse and evaluate text based rules with a Javascript-like syntax. This project was born out of the necessity to evaluate hundreds of rules that were originally written and evaluated in JavaScript, and now needed to be evaluated on the server-side, using PHP.

This library has initially been used to change and configure the behavior of certain "Workflows" (without changing actual code) in an intranet application, but it may serve a purpose elsewhere.

Install
-------

[](#install)

Via Composer

```
$ composer require nicoswd/php-rule-parser
```

Bundles
-------

[](#bundles)

This library works best with one of these bundles below, but they're not required

BundleFrameworkPackagist[nicoSWD/rule-engine-bundle](https://github.com/nicoSWD/rule-engine-bundle)Symfony[![Latest Stable Version](https://camo.githubusercontent.com/c8140d478a943d67e357b44526dfa5b9413149465dc6e40cb6dd37b81b89b6eb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e69636f7377642f73796d666f6e792d72756c652d656e67696e652d62756e646c652e737667)](https://packagist.org/packages/nicoswd/symfony-rule-engine-bundle)Usage Examples
--------------

[](#usage-examples)

Test if a value is in a given array

```
$variables = [
    'coupon_code' => (string) $_POST['coupon_code'],
];

$rule = new Rule('coupon_code in ["summer_discount", "summer21"]', $variables);
var_dump($rule->isTrue()); // bool(true)
```

Performing a regular expression

```
$variables = [
    'coupon_code' => (string) $_POST['coupon_code'],
];

$rule = new Rule('coupon_code.test(/^summer20[0-9]{2}$/) == true', $variables);
var_dump($rule->isTrue()); // bool(true)
```

Test if a value is between a given range

```
$variables = ['points' => 80];

$rule = new Rule('points >= 50 && points  300', $variables);
var_dump($rule->isTrue()); // bool(true)
```

For security reasons, PHP's magic methods like `__construct` and `__destruct` cannot be called from within rules. However, `__call` will be invoked automatically if available, unless the called method is defined.

Built-in Methods
----------------

[](#built-in-methods)

NameExamplecharAt`"foo".charAt(2) === "o"`concat`"foo".concat("bar", "baz") === "foobarbaz"`endsWith`"foo".endsWith("oo") === true`startsWith`"foo".startsWith("fo") === true`indexOf`"foo".indexOf("oo") === 1`join`["foo", "bar"].join(",") === "foo,bar"`replace`"foo".replace("oo", "aa") === "faa"`split`"foo-bar".split("-") === ["foo", "bar"]`substr`"foo".substr(1) === "oo"`test`"foo".test(/oo$/) === true`toLowerCase`"FOO".toLowerCase() === "foo"`toUpperCase`"foo".toUpperCase() === "FOO"`Built-in Functions
------------------

[](#built-in-functions)

NameExampleparseInt`parseInt("22aa") === 22`parseFloat`parseFloat("3.1") === 3.1`Supported Operators
-------------------

[](#supported-operators)

TypeDescriptionOperatorComparisongreater than&gt;Comparisongreater than or equal to&gt;=Comparisonless than&lt;Comparisonless or equal to&lt;=Comparisonequal to==Comparisonnot equal to!=Comparisonidentical===Comparisonnot identical!==ContainmentcontainsinContainmentdoes not containnot inLogicaland&amp;&amp;Logicalor||Error Handling
--------------

[](#error-handling)

Both, `$rule->isTrue()` and `$rule->isFalse()` will throw an exception if the syntax is invalid. These calls can either be placed inside a `try` / `catch` block, or it can be checked prior using `$rule->isValid()`.

```
$ruleStr = '
    (2 == 2) && (
        1 < 3 && 3 == 2 ( // Missing and/or before parentheses
            1 == 1
        )
    )';

$rule = new Rule($ruleStr);

try {
    $rule->isTrue();
} catch (\Exception $e) {
    echo $e->getMessage();
}
```

Or alternatively:

```
if (!$rule->isValid()) {
    echo $rule->getError();
}
```

Both will output: `Unexpected token "(" at position 25 on line 3`

Syntax Highlighting
-------------------

[](#syntax-highlighting)

A custom syntax highlighter is also provided.

```
use nicoSWD\Rule;

$ruleStr = '
    // This is true
    2 < 3 && (
        // This is false
        foo in [4, 6, 7] ||
        // True
        [1, 4, 3].join("") === "143"
    ) && (
        // True
        "foo|bar|baz".split("|" /* uh oh */) === ["foo", /* what */ "bar", "baz"] &&
        // True
        bar > 6
    )';

$highlighter = new Rule\Highlighter\Highlighter(new Rule\Tokenizer());

// Optional custom styles
$highlighter->setStyle(
    TokenType::VARIABLE,
    'color: #007694; font-weight: 900;'
);

echo $highlighter->highlightString($ruleStr);
```

Outputs:

[![Syntax preview](https://camo.githubusercontent.com/419d9729598dbda3eda70dff160783667ba5ffcf649805633cb1328e490e2b67/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f662e636c2e6c792f6974656d732f307931623073304a327632763175334f3146334d2f53637265656e25323053686f74253230323031352d30382d3035253230617425323031322e31352e32312e706e67)](https://camo.githubusercontent.com/419d9729598dbda3eda70dff160783667ba5ffcf649805633cb1328e490e2b67/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f662e636c2e6c792f6974656d732f307931623073304a327632763175334f3146334d2f53637265656e25323053686f74253230323031352d30382d3035253230617425323031322e31352e32312e706e67)

Notes
-----

[](#notes)

- Parentheses can be nested, and will be evaluated from right to left.
- Only value/variable comparison expressions with optional logical ANDs/ORs, are supported.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Testing
-------

[](#testing)

```
$ composer test
```

Contributing
------------

[](#contributing)

Pull requests are very welcome! If they include tests, even better. This project follows PSR-2 coding standards, please make sure your pull requests do too.

To Do
-----

[](#to-do)

- Support for object properties (foo.length)
- Support for returning actual results, other than true or false
- Support for array / string dereferencing: "foo"\[1\]
- Don't force boolean comparison for tokens that are already booleans. `my_func() && 2 > 1` should work
- Change regex and implementation for method calls. ".split(" should not be the token
- Add / implement missing methods
- Add "typeof" construct
- Do math (?)
- Allow string concatenating with "+"
- Invalid regex modifiers should not result in an unknown token
- Duplicate regex modifiers should throw an error
- Add support for function calls
- Support for regular expressions
- Fix build on PHP 7 / Nightly
- Allow variables in arrays
- Verify function and method name spelling (.tOuPpErCAse() is currently valid)
- ...

License
-------

[](#license)

[![License](https://camo.githubusercontent.com/049d999f5000a7a008d2a2fb18594297ff8880fb559b4cce6b011c87d1b24113/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6e69636f5357442f7068702d72756c652d7061727365722e737667)](https://packagist.org/packages/nicoswd/php-rule-parser)

###  Health Score

58

—

FairBetter than 98% of packages

Maintenance64

Regular maintenance activity

Popularity47

Moderate usage in the ecosystem

Community26

Small or concentrated contributor base

Maturity81

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 88.5% 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

Every ~169 days

Recently: every ~486 days

Total

23

Last Release

221d ago

PHP version history (6 changes)0.3.0PHP &gt;=5.4

0.5.0PHP ^7.0

0.6.0PHP ^7.1

0.6.1PHP &gt;=7.1

0.7.0PHP &gt;=8.0

v0.8PHP &gt;=8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/0e1cb99ed5c45d41926e55a1a0868f9ecd1b71b026ec8396aef537515786f244?d=identicon)[nicoSWD](/maintainers/nicoSWD)

---

Top Contributors

[![nicoSWD](https://avatars.githubusercontent.com/u/205852?v=4)](https://github.com/nicoSWD "nicoSWD (23 commits)")[![altesack](https://avatars.githubusercontent.com/u/682018?v=4)](https://github.com/altesack "altesack (1 commits)")[![mend-bolt-for-github[bot]](https://avatars.githubusercontent.com/in/16809?v=4)](https://github.com/mend-bolt-for-github[bot] "mend-bolt-for-github[bot] (1 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")

---

Tags

brmsbusiness-rulesdslevaluatorparserphpphp-rule-enginerule-enginerule-parserrule-systemworkflowjavascriptparserworkflowtokenizerDSLruleenginehighlighterevaluator

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/nicoswd-php-rule-parser/health.svg)

```
[![Health](https://phpackages.com/badges/nicoswd-php-rule-parser/health.svg)](https://phpackages.com/packages/nicoswd-php-rule-parser)
```

###  Alternatives

[behat/gherkin

Gherkin DSL parser for PHP

1.1k176.3M97](/packages/behat-gherkin)[thunderer/shortcode

Advanced shortcode (BBCode) parser and engine for PHP

3892.6M44](/packages/thunderer-shortcode)[thadafinser/user-agent-parser

UserAgent parsing done right http://useragent.mkf.solutions/

249316.9k2](/packages/thadafinser-user-agent-parser)[madorin/matex

PHP Mathematical expression parser and evaluator

1161.2M1](/packages/madorin-matex)[jeremeamia/functionparser

Function parser for PHP functions, methods, and closures

48169.7k6](/packages/jeremeamia-functionparser)[smuuf/php-peg

PEG parser generator for PHP.

12118.4k3](/packages/smuuf-php-peg)

PHPackages © 2026

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