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

v1.0(2mo ago)13181.4k↓48.6%18[1 issues](https://github.com/nicoSWD/php-rule-parser/issues)7MITPHPPHP &gt;=8.5CI passing

Since Jul 22Pushed 2mo 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 today

READMEChangelog (10)Dependencies (5)Versions (33)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)[![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)[![Code Coverage](https://camo.githubusercontent.com/a160d9f4740fe9cf1d2ac7f18072eb82129762088a91d18e35a51f8e0fd43c6c/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6e69636f5357442f7068702d72756c652d706172736572)](https://codecov.io/gh/nicoSWD/php-rule-parser)

A PHP library that parses and evaluates boolean expressions using a JavaScript-like syntax. It supports variables, comparison and logical operators, arithmetic, regular expressions, arrays, string methods, and function calls, all from plain text rules.

Install
-------

[](#install)

Via Composer

```
composer install nicoswd/php-rule-parser
```

Usage Examples
--------------

[](#usage-examples)

E-commerce: Validate coupon eligibility

```
$variables = [
    'cart_total'     => 120,
    'user_tier'      => 'gold',
    'is_blacklisted' => false,
];

$rule = new Rule('
    cart_total >= 50 &&
    user_tier in ["gold", "platinum"] &&
    !is_blacklisted
', $variables);

var_dump($rule->isTrue()); // bool(true) — eligible for discount
```

Access control: Check user permissions

```
$variables = [
    'role'         => 'editor',
    'is_suspended' => false,
];

$rule = new Rule('role in ["admin", "editor"] && !is_suspended', $variables);
var_dump($rule->isTrue()); // bool(true) — access granted
```

Pricing: Calculate order total with conditions

```
$variables = [
    'base_price' => 29.99,
    'tax_rate'   => 21,
    'quantity'   => 3,
];

$rule = new Rule('(base_price + (base_price * tax_rate / 100)) * quantity', $variables);
var_dump($rule->result()); // float(108.8571...) — total with tax
```

Form validation: Check input constraints

```
$variables = [
    'age'     => 25,
    'country' => 'US',
];

$rule = new Rule('age >= 18 && country in ["US", "CA", "UK"]', $variables);
var_dump($rule->isTrue()); // bool(true) — valid registration
```

Notification routing: Target specific users

```
$variables = [
    'plan'                 => 'pro',
    'last_login'           => 3,
    'notification_opt_out' => false,
];

$rule = new Rule('
    plan in ["pro", "enterprise"] &&
    last_login < 7 &&
    !notification_opt_out
', $variables);

var_dump($rule->isTrue()); // bool(true) — send notification
```

Feature flags: Roll out features gradually

```
$variables = [
    'user_id' => 7,
];

$rule = new Rule('user_id % 10 < 3', $variables);
var_dump($rule->isTrue()); // bool(true) — feature enabled for this user
```

String manipulation: Format user data

```
$variables = [
    'firstName' => 'John',
    'lastName'  => 'Doe',
];

$rule = new Rule('firstName.toUpperCase() + " " + lastName.toUpperCase()', $variables);
var_dump($rule->result()); // string("JOHN DOE")
```

Object method calls: Evaluate complex conditions

```
class Subscription
{
    public function isActive(): bool
    {
        return true;
    }

    public function daysUntilExpiry(): int
    {
        return 15;
    }
}

$variables = [
    'subscription' => new Subscription(),
];

$rule = new Rule('subscription.isActive() && subscription.daysUntilExpiry() > 7', $variables);
var_dump($rule->isTrue()); // bool(true) — subscription is active and not expiring soon
```

Arithmetic: Operator precedence

```
$rule = new Rule('2 + 3 * 4 == 14');
var_dump($rule->isTrue()); // bool(true) - multiplication before addition

$rule = new Rule('(2 + 3) * 4 == 20');
var_dump($rule->isTrue()); // bool(true) - parentheses override precedence
```

Arithmetic: Unary operators

```
$rule = new Rule('-5 * 3 == -15');
var_dump($rule->isTrue()); // bool(true) - unary minus

$rule = new Rule('!false');
var_dump($rule->isTrue()); // bool(true) - logical NOT

$rule = new Rule('!(1 == 2)');
var_dump($rule->isTrue()); // bool(true) - NOT with comparison
```

Note

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")`startsWith`"foo".startsWith("fo")`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$/)`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||Arithmeticaddition+Arithmeticsubtraction-Arithmeticmultiplication\*Arithmeticdivision/Arithmeticmodulo%Unarynegation-Unarylogical NOT!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 validity can be checked beforehand 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->error;
}
```

Both will output: `Unexpected "(" at position 28`

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

[](#syntax-highlighting)

A custom syntax highlighter is also provided.

```
use nicoSWD\Rule\Highlighter\Highlighter;
use nicoSWD\Rule\TokenStream\Token\TokenType;

$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 Highlighter();

// 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)

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-12](https://www.php-fig.org/psr/psr-12/) coding standards, please make sure your pull requests do too.

To Do
-----

[](#to-do)

- Support for object properties (foo.length)
- Support for array / string dereferencing: "foo"\[1\]
- Support for returning actual results, other than true or false
- Don't force boolean comparison for tokens that are already booleans. `my_func() && 2 > 1` should work
- Allow string concatenating with "+"
- 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)
- Change regex and implementation for method calls
- Add / implement missing methods
- Invalid regex modifiers should not result in an unknown token
- ...

License
-------

[](#license)

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

###  Health Score

67

—

FairBetter than 99% of packages

Maintenance87

Actively maintained with recent releases

Popularity46

Moderate usage in the ecosystem

Community26

Small or concentrated contributor base

Maturity92

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 91.4% 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 ~171 days

Recently: every ~480 days

Total

24

Last Release

66d ago

Major Versions

v0.8 → v1.02026-04-29

PHP version history (7 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

v1.0PHP &gt;=8.5

### 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 (32 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

Code StylePHP\_CodeSniffer

### 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.1k184.9M138](/packages/behat-gherkin)[thunderer/shortcode

Advanced shortcode (BBCode) parser and engine for PHP

3952.8M51](/packages/thunderer-shortcode)[thadafinser/user-agent-parser

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

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

PHP Mathematical expression parser and evaluator

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

Function parser for PHP functions, methods, and closures

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

PEG parser generator for PHP.

13126.6k4](/packages/smuuf-php-peg)

PHPackages © 2026

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