PHPackages                             iak/regexbuilder - 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. iak/regexbuilder

ActiveLibrary

iak/regexbuilder
================

A fluent api that simplifies writing regular expressions

v1.0(8y ago)522MITPHP

Since Oct 24Pushed 8y ago1 watchersCompare

[ Source](https://github.com/iaK/regexbuilder)[ Packagist](https://packagist.org/packages/iak/regexbuilder)[ RSS](/packages/iak-regexbuilder/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (3)Versions (2)Used By (0)

Regex builder
=============

[](#regex-builder)

A fluent api that simplifies writing regular expressions. *(for the ones of us who always forget the syntax)*

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

[](#installation)

Grab it using composer

```
$ composer require iak/regexbuilder
```

```
{
    "require": {
        "iak/regexbuilder": "^1.0"
    }
}
```

Simple as that :)

Introduction
------------

[](#introduction)

This library is for all of us that find regular expressions hard to write and impossible to remember all the different flags, look aheads, capture groups etc.

Instead of spending that half hour searching stackoverflow, I hope you can easily whip up a pattern using this lib.

Note. a basic understading of how regular expressions is still needed.

Quick start
-----------

[](#quick-start)

First of all, use the class at the top of you file,

```
use RegexBuilder\Regex;
```

Now you can use it like this

```
$string = "wow! this is cool!"

$match = Regex::word("wow")->symbol("!")->match($string); // wow!
```

Or maybe something more advanced (and demostrating some different ways of using the library)

```
    // Match an email address

    $email = "info@isakberglind.se";

    Regex::group("a-z0-9_-.")
        ->oneOrMore()
        ->symbol("@")
        ->group("a-z0-9_-].")
        ->oneOrMore()
        ->symbol(".")
        ->group("a-z")
        ->count(2,6)
        ->match($email);

    // a simple url-matcher

    $url = "http://www.landslide-design.se";

    Regex::word(["http", "https", "ftp"])
        ->symbols("://")
        ->capture(function ($query) {
            return $query->symbols("www.");
        })
        ->optional()
        ->group("a-zA-Z0-9@:._")
        ->count(2, 255)
        ->symbols(".")
        ->group(function ($query) {
            return $query->range("a", "z");
        })
        ->count(2, 6)
        ->group(function ($query) {
            return $query
                ->range("a", "z")
                ->range("A", "Z")
                ->range(0, 9)
                ->symbols("@:_.?//");
        })
        ->zeroOrMore()
        ->match($url);
```

Documentation
=============

[](#documentation)

Words, patterns and symbols
---------------------------

[](#words-patterns-and-symbols)

#### word(mixed $word = null)

[](#wordmixed-word--null)

*Matches provided word, array of words or any word*

```
    $string = "This is a hard example!";

    Regex::word("simple")->replace("simple", $string);   // This is a simple example

    Regex::word(["This", "simple", "example"])->matchAll($string); // ["this", "example"]

    Regex::word()->matchAll($string) // ["this", "is", "a", "hard", "example"]
```

#### notWord()

[](#notword)

*Matches anything but a word*

```
    $string = "Hi!!!!! What's up?";

    Regex::notWord()->match($string); // '!!!! '
```

#### symbols(string $symbols)

[](#symbolsstring-symbols)

*Matches provided symbols (escapes string, if you don't want that, use "pattern")*

```
    $string = "This is &!^@? awesome!"

    Regex::symbols("&!^@?")->replace("totally", $string) // This is totally awesome
```

#### pattern(string $pattern)

[](#patternstring-pattern)

*Matches provided pattern*
*Aliases: raw()*

```
    $string = "kickass example text";

    Regex::pattern("(example|text)")->matchAll($string); // ["example", "text"]
```

Characters
----------

[](#characters)

You can match a bunch of characters using the following helper methods

```
    Regex::digit();
    Regex::notDigit();
    Regex::whitespace();
    Regex::notWhitespace();
    Regex::char();
    Regex::notChar();
    Regex::hexDigit();
    Regex::octalDigit();
    Regex::newLine();
    Regex::carriageReturn();
    Regex::tab();
    Regex::verticalTab();
    Regex::formFeed();
    Regex::space();
    Regex::any();
```

Quantifiers
-----------

[](#quantifiers)

#### oneOrMore()

[](#oneormore)

*Matches one or more of preceding group, character or character set.*

```
    $string = "Here are some numbers 123456. Cool huh?"

    Regex::digit()->oneOrMore()->match($string) // 123456
```

#### zeroOrMore()

[](#zeroormore)

*Matches zero or more*

```
    $string = "AA A1A A12A";

    Regex::char()->digit()->zeroOrMore()->char()->matchAll($string) // ["AA", "A1A", "A12A"]
```

#### count(int $count/$start, int $end = null)

[](#countint-countstart-int-end--null)

*Matches the specified amount or the minimum and maximun count*

```
    $string = "1 12 123 1234";

    // Specify the exact count to match..
    Regex::digit()->count(3)->match($string); // 123

    // Or a minimum and maximum..
    Regex::digit()->count(2,4)->matchAll($string); // [12, 123, 1234]
```

Groups &amp; Character sets
---------------------------

[](#groups--character-sets)

#### range(mixed $start, $mixed $end)

[](#rangemixed-start-mixed-end)

*Specifies a range, made especially for working with character sets*

```
    Regex::range("a", "z"); // a-z
```

#### group(mixed $pattern/$callback)

[](#groupmixed-patterncallback)

*Creates a character set*

```
    // Using a callback

    Regex::group(function ($builder) {
        return $builder->range("a", "z");
    });

    // Using a raw pattern

    Regex::group("a-z");

    // Produces the same;  [a-z]
```

Capture groups
--------------

[](#capture-groups)

#### capture(callable $callback = null)

[](#capturecallable-callback--null)

*Creates a capture group*

```
    $string = "Capture this if you can!";

    // you can either capture the previous statement..

    Regex::word("this")->capture();

    // .. or using a callback

    Regex::capture(function ($builder) {
        return $builder->word("this");
    });

    // Produces the same; (this)
```

#### opionalCapture(mixed $pattern/$callback)

[](#opionalcapturemixed-patterncallback)

*Creates a non capturing group*

```
    $string = "Do not capture this if you can!";

    // you can either capture the previous statement..

    Regex::word("this")->capture();

    // .. or using a callback

    Regex::capture(function ($builder) {
        return $builder->word("this");
    });

    // Produces the same; (?:this)?

```

#### startCapture() *and* endCapture()

[](#startcapture-and-endcapture)

*You can also surround what you want to capture with these methods*

```
    $string = "Capture this if you can";

    Regex::startCapture()->word("this")->endCapture(); // (this)
```

Look aheads &amp; look behinds
------------------------------

[](#look-aheads--look-behinds)

#### behind(mixed $pattern/$callback)

[](#behindmixed-patterncallback)

*Creates a look behind*
*Aliases: beginsWith(), before()*

```
    $string = "important";

    // Using a callback..
    Regex::behind(function ($builder) {
        return $builder->symbols("");
    })
    ->word()
    ->match($string);

    // .. or a raw pattern..
    Regex::behind("\*\*\*\*")->word()->match($string);

    // important
```

#### after(mixed $pattern/$callback)

[](#aftermixed-patterncallback)

*Creates a look ahead, works exactly like before()*
*Aliases: endsWith()*

Other helpers
-------------

[](#other-helpers)

#### optional(mixed $characters/$start = null, $length = null)

[](#optionalmixed-charactersstart--null-length--null)

*Makes capture group, character set or character optional*

```
    $string = "Is it spelled color or colour?";

    // Using a characters
    Regex::word("colour")->optional("u")->matchAll($string); // ["color", "colour"]

    // Using a start and a length
    Regex::word("colour")->optional(4,1)->matchAll($string); // ["color", "colour"]

    // Make last statement optinal

    Regex::symbols("colo")->char("u")->optional()->symbols("r")->matchAll($string); // ["color", "colour"]
```

#### escape(string $pattern)

[](#escapestring-pattern)

*Escapes provided pattern*

```
    $pattern = "^[]$group("a-zA-Z_")->oneOrMore()->match($string); // @Isak_Berglind
```

#### matchAll($string)

[](#matchallstring)

*Matches all of the occurences of the built up pattern*
*Note! only return the match. If you want all capture groups, use matchAllWithGroups()*

```
    $string = "this is as good as it gets";

    Regex::any()->symbol("s")->matchAll($string); // ["is", "is", "as", "as", "ts"]
```

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity63

Established project with proven stability

 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

3124d ago

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

regexregular expressions

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/iak-regexbuilder/health.svg)

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

###  Alternatives

[composer/pcre

PCRE wrapping library that offers type-safe preg\_\* replacements.

693313.8M34](/packages/composer-pcre)[spatie/regex

A sane interface for php's built in preg\_\* functions

1.1k17.1M59](/packages/spatie-regex)[gherkins/regexpbuilderphp

PHP port of thebinarysearchtree/regexpbuilderjs

1.4k163.0k1](/packages/gherkins-regexpbuilderphp)[jasny/twig-extensions

A set of useful Twig filters

10710.2M8](/packages/jasny-twig-extensions)[rawr/t-regx

PHP regular expression brought up to modern standards.

451157.3k3](/packages/rawr-t-regx)[milwad/laravel-validate

The Laravel-Validate package enhanced Laravel validation capabilities with custom rules and methods for simplified and efficient validation logic.

59739.5k1](/packages/milwad-laravel-validate)

PHPackages © 2026

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