PHPackages                             aegisora/regex-rule - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. aegisora/regex-rule

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

aegisora/regex-rule
===================

Regex Rule provides a simple, rule-based regular expression validation implementation for the Aegisora ecosystem

v1.0.0(today)01↑2900%MITPHPPHP &gt;=7.4

Since Aug 24Pushed todayCompare

[ Source](https://github.com/Aegisora/regex-rule)[ Packagist](https://packagist.org/packages/aegisora/regex-rule)[ Docs](https://github.com/Aegisora/regex-rule)[ RSS](/packages/aegisora-regex-rule/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (4)Versions (2)Used By (0)

Aegisora Regex Rule
===================

[](#aegisora-regex-rule)

[![Latest Version](https://camo.githubusercontent.com/8ea4a9d6bac6f7da5e03428638d00867216489da83d8379b22873c7db41bb37c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f61656769736f72612f72656765782d72756c653f7374796c653d666c61742d737175617265)](https://packagist.org/packages/aegisora/regex-rule)[![Total Downloads](https://camo.githubusercontent.com/aacace11554ac8b23ed69920ce861e39f2a033bbb269ba57ed70f40b868b1a25/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f61656769736f72612f72656765782d72756c653f7374796c653d666c61742d737175617265)](https://packagist.org/packages/aegisora/regex-rule)[![Code Coverage Badge](./badge.svg)](./badge.svg)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHPStan Badge](https://camo.githubusercontent.com/83dd3d35cebed0eab9ee97ff1a5849c1344cda6a8ee9cac2cda20f5aa55b67bd/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230392d627269676874677265656e2e7376673f7374796c653d666c6174)](https://camo.githubusercontent.com/83dd3d35cebed0eab9ee97ff1a5849c1344cda6a8ee9cac2cda20f5aa55b67bd/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230392d627269676874677265656e2e7376673f7374796c653d666c6174)

Regex Rule provides a simple, rule-based regular expression validation implementation for the Aegisora ecosystem.

It is built on top of [`aegisora/rule-contract`](https://github.com/Aegisora/rule-contract) and follows its strict validation architecture, ensuring consistent and predictable behavior across applications.

This rule is useful for validating user input, form fields, usernames, slugs, email addresses, phone numbers, API request parameters, and any other string that must match a specific pattern.

---

📑 Table of Contents
-------------------

[](#-table-of-contents)

- [Features](#-features)
- [Installation](#-installation)
- [Core Concept](#-core-concept)
- [Basic Usage](#-basic-usage)
- [Valid vs Invalid](#-valid-vs-invalid)
- [Validation Result](#-validation-result)
- [Guardian Usage](#-guardian-usage)
- [Real-World Examples](#-real-world-examples)
- [Factory Methods](#-factory-methods)
- [Architecture](#-architecture)
- [License](#-license)
- [Contributing](#-contributing)
- [Support](#-support)

---

✨ Features
----------

[](#-features)

- 🔹 Lightweight and dependency-free except `aegisora/rule-contract`
- 🔹 Validates a string against any PCRE regular expression
- 🔹 Supports the full pattern syntax and flags (`i`, `u`, `m`, `s`, ...)
- 🔹 Rejects non-string input as an invalid context
- 🔹 Surfaces broken patterns and runtime PCRE failures as execution errors instead of a silent `false`
- 🔹 Fully compatible with Aegisora validation pipeline
- 🔹 Strict `Context` → `Result` validation flow
- 🔹 No raw booleans — only structured results
- 🔹 Safe execution via base `Rule` abstraction
- 🔹 Expressive factory API
- 🔹 Ready to use out of the box

---

📦 Installation
--------------

[](#-installation)

```
composer require aegisora/regex-rule
```

---

🚀 Core Concept
--------------

[](#-core-concept)

This package implements a single validation rule:

- accepts a string value via `Context`
- checks whether the string matches the configured regular expression
- returns a standardized `Result`

Under the hood it wraps the common boilerplate:

```
if (preg_match($pattern, $value) !== 1) {
    // value does not match the pattern
}
```

into a reusable rule that reports its outcome through a `Result` object instead of a raw boolean, and turns PCRE failures into explicit exceptions.

---

🏗️ Basic Usage
--------------

[](#️-basic-usage)

```
use Aegisora\RuleContract\Models\Context;
use Aegisora\Rules\RegexRule;

$result = RegexRule::create('/^[a-z0-9_-]+$/')->validate(Context::create('user_name-1'));

if ($result->isValid()) {
    // value matches the pattern
} else {
    // value does not match the pattern
}
```

The rule can also be instantiated directly:

```
$result = (new RegexRule('/^[a-z0-9_-]+$/'))->validate(Context::create('user_name-1'));
```

---

✅ Valid vs Invalid
------------------

[](#-valid-vs-invalid)

The rule passes when the string matches the configured pattern and fails otherwise.

### Anchored patterns

[](#anchored-patterns)

```
RegexRule::create('/^[a-z]+$/')->validate(Context::create('abc'));      // valid   — the whole string matches
RegexRule::create('/^[a-z]+$/')->validate(Context::create('abc123'));   // invalid — digits are not allowed

RegexRule::create('/^\d+$/')->validate(Context::create('12345'));       // valid   — only digits
RegexRule::create('/^\d+$/')->validate(Context::create(''));            // invalid — at least one digit is required
```

### Unanchored patterns

[](#unanchored-patterns)

```
RegexRule::create('/\d+/')->validate(Context::create('abc123'));        // valid   — a digit is found somewhere
RegexRule::create('/\d+/')->validate(Context::create('abcdef'));        // invalid — no digit found
```

### Flags

[](#flags)

```
RegexRule::create('/^abc$/i')->validate(Context::create('ABC'));        // valid   — case-insensitive match
RegexRule::create('/^abc$/')->validate(Context::create('ABC'));         // invalid — case matters without the i flag

RegexRule::create('/^[а-яё]+$/ui')->validate(Context::create('Привет')); // valid  — u flag enables UTF-8 mode
```

---

🧪 Validation Result
-------------------

[](#-validation-result)

If the string matches the pattern, the rule returns a valid result.

`$result->isValid(); // true`

If the string does not match the pattern, the rule returns an invalid result.

```
$result->isValid(); // false
$result->getFailedRuleCode(); // regex_rule
```

If the context value is not a string, the rule throws:

`Aegisora\RuleContract\Exceptions\InvalidRuleContextException`

If the pattern is invalid, or the match fails at runtime (e.g. the backtrack limit is exceeded or the subject is not valid UTF-8 under the `u` flag), the rule throws:

`Aegisora\RuleContract\Exceptions\RuleExecutionException`

---

🔗 Guardian Usage
----------------

[](#-guardian-usage)

This rule can be used together with `aegisora/guardian` to build fluent validation pipelines.

```
use Aegisora\Guardian\Guardian;
use Aegisora\Rules\RegexRule;
use App\Exceptions\InvalidUsernameException;

$guardian = new Guardian();

$guardian
    ->that($username)
    ->must(RegexRule::create('/^[a-z0-9_-]{3,32}$/'), new InvalidUsernameException())
    ->validate();
```

If the value does not match the pattern, `Guardian` throws the provided domain exception.

---

🧭 Real-World Examples
---------------------

[](#-real-world-examples)

Regex Rule is useful for enforcing format constraints before values are persisted or processed.

Examples

```
User Registration:

require a username of lowercase letters, digits, underscores and hyphens

```

```
Slugs:

ensure a URL slug contains only lowercase letters, digits and hyphens

```

```
Identifiers:

validate that a code matches a fixed structured format

```

```
API:

reject request parameters that do not match the expected shape

```

---

🧩 Factory Methods
-----------------

[](#-factory-methods)

`RegexRule::create($pattern);`

- creates a rule that passes when the value matches the PCRE `$pattern` (delimiters and flags included)

`new RegexRule($pattern);`

- equivalent to `RegexRule::create($pattern)`

`RegexRule::create($pattern)->validate($context);`

- `$context` — `Context` wrapping the string value to validate

---

🏛️ Architecture
---------------

[](#️-architecture)

This package relies on [`aegisora/rule-contract`](https://github.com/Aegisora/rule-contract).

Flow:

1. `validate()` is called
2. `Context` is passed in
3. The configured pattern is checked; a broken pattern raises `RuleExecutionException`
4. The string value is extracted from context (non-strings raise `InvalidRuleContextException`)
5. The value is matched against the pattern with `preg_match()`; a PCRE runtime failure raises `RuleExecutionException`
6. `Result` is returned — valid on match, invalid with the `regex_rule` code on no match

All logic is safely handled by Rule contract.

---

⚖️ License
----------

[](#️-license)

This package is open-source and licensed under the MIT License. See the [LICENSE](LICENSE) for details.

---

🌱 Contributing
--------------

[](#-contributing)

Contributions are welcome and greatly appreciated! See the [CONTRIBUTING](CONTRIBUTING.md) for details.

---

🌟 Support
---------

[](#-support)

If you find this project useful, please consider giving it a star on GitHub!

It helps the project grow and motivates further development.

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance100

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

 Bus Factor1

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

0d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/81402dcd0a07ad550b7f80f5871e7c302770b29d4c73a52fc35ba697f702d56e?d=identicon)[arslanim](/maintainers/arslanim)

---

Top Contributors

[![arslanim](https://avatars.githubusercontent.com/u/22678154?v=4)](https://github.com/arslanim "arslanim (9 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")

---

Tags

aegisoraaegisora-ecosystempattern-matchingpatternspcrephppreg-matchregexregexpregular-expressionrulesstring-validationvalidationphpvalidationregexPCREregular expressionrulepatternregexpPattern Matchingpreg\_matchstring validationaegisoraaegisora-ecosystem

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/aegisora-regex-rule/health.svg)

```
[![Health](https://phpackages.com/badges/aegisora-regex-rule/health.svg)](https://phpackages.com/packages/aegisora-regex-rule)
```

PHPackages © 2026

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