PHPackages                             regex-guard/regex-guard - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. regex-guard/regex-guard

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

regex-guard/regex-guard
=======================

A wrapper that allows you to validate regular expressions and handle normally uncatchable PCRE compilation warnings

1.1.0(11y ago)24530.3k↓48%48MITPHP

Since Aug 8Pushed 10y ago3 watchersCompare

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

READMEChangelog (3)Dependencies (1)Versions (4)Used By (8)

RegexGuard
==========

[](#regexguard)

[![Build Status](https://camo.githubusercontent.com/e50a22aa9649fe1161f8efcfc6d1354dd2dbc573bd42e96d7033c66fbd51b6e3/68747470733a2f2f7472617669732d63692e6f72672f6d617263696f416c6d6164612f72656765782d67756172642e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/marcioAlmada/regex-guard "Travis Build")[![Coverage Status](https://camo.githubusercontent.com/6b8a3090bf75a9be8035cf9d2640e66568ecf140327be95810a60f403a944a18/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6d617263696f416c6d6164612f72656765782d67756172642f62616467652e706e673f6272616e63683d6d6173746572)](https://coveralls.io/r/marcioAlmada/regex-guard?branch=master "Code Coverage")[![Scrutinizer Quality Score](https://camo.githubusercontent.com/2fba6e9ae16ffe1090d6dddddbecc583d87a61eedcf5f5f0646b9316d47ddf12/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6d617263696f416c6d6164612f72656765782d67756172642f6261646765732f7175616c6974792d73636f72652e706e67)](https://scrutinizer-ci.com/g/marcioAlmada/regex-guard/ "Code Quality")[![Latest Stable Version](https://camo.githubusercontent.com/7c23846a4682b468d5a76614b04d1b7f8117f624405bb56dfbf712aac9da8e98/68747470733a2f2f706f7365722e707567782e6f72672f72656765782d67756172642f72656765782d67756172642f762f737461626c652e706e67)](https://packagist.org/packages/regex-guard/regex-guard "Packagist")[![Total Downloads](https://camo.githubusercontent.com/4c41537100d51b41ab6c385210630e6f37c0ead858225fc7a75ace60ae8b5f35/68747470733a2f2f706f7365722e707567782e6f72672f72656765782d67756172642f72656765782d67756172642f646f776e6c6f6164732e706e67)](https://packagist.org/packages/regex-guard/regex-guard "Packagist")[![License](https://camo.githubusercontent.com/a74d433260471134a4a7a3b8ce7e3ea9917d3eeb1b31e1b33ce9da1277d2c908/68747470733a2f2f706f7365722e707567782e6f72672f72656765782d67756172642f72656765782d67756172642f6c6963656e73652e706e67)](https://packagist.org/packages/regex-guard/regex-guard "Packagist")[![SensioLabsInsight](https://camo.githubusercontent.com/7d6606fe3da9c8d83d310617b2fb32ce5134e38cde0a5352329498b856224b81/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f34353461623266322d326233332d343964612d623165382d3735646163623261333030632f6d696e692e706e67)](https://insight.sensiolabs.com/projects/454ab2f2-2b33-49da-b1e8-75dacb2a300c)[![Dependency Status](https://camo.githubusercontent.com/76d07050ab45132a1c78640ec031ee3c2ce8b748b591f3e94723d00dff1963df/68747470733a2f2f7777772e76657273696f6e6579652e636f6d2f7068702f72656765782d67756172643a72656765782d67756172642f312e302e302f62616467652e737667)](https://www.versioneye.com/php/regex-guard:regex-guard/1.0.0)[![Reference Status](https://camo.githubusercontent.com/3127bc1f5874bd5360731c0ebe7a0b3e1d69296d864b6ac7f4ad6f9b99f62367/68747470733a2f2f7777772e76657273696f6e6579652e636f6d2f7068702f72656765782d67756172643a72656765782d67756172642f7265666572656e63655f62616467652e737667)](https://www.versioneye.com/php/regex-guard:regex-guard/references)

Why?
----

[](#why)

PHP core `preg_*` functions do not offer any good way to validate a regular expression before usage. Some core functions return false for invalid regular expressions but they also emit uncatchable warnings.

**RegexGuard** is a wrapper that allows you to validate regular expressions and keep your API away from uncatchable PCRE compilation warnings.

Composer Installation
---------------------

[](#composer-installation)

```
{
  "require": {
    "regex-guard/regex-guard": "~1.0"
  }
}
```

Through terminal: `composer require regex-guard/regex-guard:~1.0` 🎱

Quick Example
-------------

[](#quick-example)

First grab a **RegexGuard** instance:

```
$guard = \RegexGuard\Factory::getGuard();
```

Validate your regex:

```
if($guard->isRegexValid($regexp)) {
    // valid
}
else {
    // invalid
}
```

And there is more...

RegexGuard API
--------------

[](#regexguard-api)

Internally, **RegexGuard** instance sandboxes all `preg_*` functions calls and handle errors in a convenient way. All `preg_*` core functions are fully represented:

#### ::isRegexValid($pattern)

[](#isregexvalidpattern)

Validates a given regexp. Returns true when PCRE string is valid, false otherwise:

```
$guard->isRegexValid('/\w{0,1}/');
// true, regex is valid

$guard->isRegexValid('/\w{1,0}/');
// false, compilation fails: quantifiers are out of order

$guard->isRegexValid('/(\w)(?2)/');
// false, compilation fails: reference to non-existent subpattern at offset 7
```

#### ::validateRegexOrFail($pattern)

[](#validateregexorfailpattern)

Validates a given regexp or throw `\RegexGuard\RegexException` if PCRE is invalid:

```
$guard->validateRegexOrFail('/(\w)(?2)/');
// throws: compilation fails: reference to non-existent subpattern at offset 7
```

#### ::match($pattern, $subject, &amp;$matches=null, $flags=0, $offset=0)

[](#matchpattern-subject-matchesnull-flags0-offset0)

Same as [preg\_match](http://php.net/manual/en/function.preg-match.php) but throws a `\RegexGuard\RegexException` when an invalid PCRE string is given:

```
try {
    if($regexGuard->match($pattern, $subject)) {
        // match
    } else {
        // no match
    }
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}
```

#### ::matchAll($pattern,$subject,&amp;$matches=null,$flags=?,$offset=0)

[](#matchallpatternsubjectmatchesnullflagsoffset0)

Same as [preg\_match\_all](http://php.net/manual/en/function.preg-match-all.php) but throws a `\RegexGuard\RegexException` when an invalid PCRE string is given:

```
try {
    $found = $regexGuard->matchAll($pattern, $subject, $matches);
    if($found) {
        foreach($matches[0] as $match) {
            //
        }
    }
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}
```

> NOTE: `$flags` default value depends on your PHP version.

#### ::filter($pattern, $subject, $limit = -1, $flags = 0)

[](#filterpattern-subject-limit---1-flags--0)

Same as [preg\_filter](http://php.net/manual/en/function.preg-filter.php) but throws a `\RegexGuard\RegexException` when an invalid PCRE string is given:

```
try {
    $result = $regexGuard->filter($pattern, $subject);
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}
```

#### ::grep($pattern, $input, $flags = 0)

[](#greppattern-input-flags--0)

Same as [preg\_grep](http://php.net/manual/en/function.preg-grep.php) but throws a `RegexGuard\RegexException` when an invalid PCRE string is given:

```
try {
    $result = $regexGuard->grep($pattern, $input);
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}
```

#### ::replace($pattern, $replace, $subject, $limit=-1, &amp;$count=null)

[](#replacepattern-replace-subject-limit-1-countnull)

Same as [preg\_replace](http://php.net/manual/en/function.preg-replace.php) but throws a `\RegexGuard\RegexException` when an invalid PCRE string is given:

```
try {
    $result = $regexGuard->replace($pattern, $replacement, $subject);
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}
```

#### ::split($pattern, $subject, $limit = -1, $flags = 0)

[](#splitpattern-subject-limit---1-flags--0)

Same as [preg\_split](http://php.net/manual/en/function.preg-split.php) but throws a `\RegexGuard\RegexException` when an invalid PCRE string is given:

```
try {
    $list = $regexGuard->split($pattern, $subject);
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}
```

Avoiding Exceptions
-------------------

[](#avoiding-exceptions)

You can avoid `try catch` blocks by telling **RegexGuard** not to throw exceptions when an invalid regular expression is encountered:

```
$guard = \RegexGuard\Factory::getGuard()->throwOnException(false);
```

This can be useful to avoid verbosity when your API needs to validate regexp arguments all over the place, but you will have to be **extra careful** when checking results!

```
if(1 === $guard->match('#foo#y', 'bar')) {
// ^ strict check            ^ bad regex: Unknown modifier 'y' on line 1
}
```

Manual Instantiation
--------------------

[](#manual-instantiation)

```
use RegexGuard\ErrorHandler;
use RegexGuard\Sandbox;
use RegexGuard\RegexGuard;

$guard = new RegexGuard(new Sandbox(new ErrorHandler));
```

Features
--------

[](#features)

- No need for `@preg_match`, `@preg_match_all`...
- No need to use regexp to validate a given regexp or any other crappy solution
- Aims to be 100% compatible with PHP `preg_*` core functions
- Faster and more reliable than `@` + `preg_*` calls
- Compatible with xdebug.scream

Contribution Guide
------------------

[](#contribution-guide)

1. Fork [regex-guard](https://github.com/marcioAlmada/regex-guard/fork)
2. Clone forked repository
3. Install composer dependencies `$ composer install`
4. Run unit tests `$ phpunit`
5. Modify code: correct bug, implement feature
6. Back to step 4
7. Pull request to master branch

Copyright
---------

[](#copyright)

Copyright (c) 2014 Márcio Almada. Distributed under the terms of an MIT-style license. See LICENSE for details.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity46

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 93.2% 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 ~20 days

Total

3

Last Release

4307d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e6b4f6d6d37192719fb4d4d03bbdb9e866972a2b6556da9967b10b35843809f1?d=identicon)[marcioAlmada](/maintainers/marcioAlmada)

---

Top Contributors

[![marcioAlmada](https://avatars.githubusercontent.com/u/227395?v=4)](https://github.com/marcioAlmada "marcioAlmada (55 commits)")[![reiz](https://avatars.githubusercontent.com/u/652130?v=4)](https://github.com/reiz "reiz (2 commits)")[![debo](https://avatars.githubusercontent.com/u/493257?v=4)](https://github.com/debo "debo (1 commits)")[![gsouf](https://avatars.githubusercontent.com/u/3215399?v=4)](https://github.com/gsouf "gsouf (1 commits)")

---

Tags

regexPCREpregutilssupportregexp

### Embed Badge

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

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

###  Alternatives

[composer/pcre

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

707347.9M60](/packages/composer-pcre)[spatie/regex

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

1.1k19.8M70](/packages/spatie-regex)[rawr/t-regx

PHP regular expression brought up to modern standards.

457166.9k7](/packages/rawr-t-regx)[jasny/twig-extensions

A set of useful Twig filters

10611.0M12](/packages/jasny-twig-extensions)[niklongstone/regex-reverse

Regular Expression reverter, generates a string from a provided regular expression

105161.8k5](/packages/niklongstone-regex-reverse)[kozz/emoji-regex

Emoji regex parser

31175.5k](/packages/kozz-emoji-regex)

PHPackages © 2026

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