PHPackages                             spatie/regex - 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. spatie/regex

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

spatie/regex
============

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

3.1.1(4y ago)1.1k17.1M—0.7%5020MITPHPPHP ^8.0|^8.1CI passing

Since Aug 17Pushed 3mo ago10 watchersCompare

[ Source](https://github.com/spatie/regex)[ Packagist](https://packagist.org/packages/spatie/regex)[ Docs](https://github.com/spatie/regex)[ Fund](https://spatie.be/open-source/support-us)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-regex/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (18)Used By (20)

Making regex great again
========================

[](#making-regex-great-again)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6310ee608208a8b3c4704fea41c9bbb5dbb186177b168e13a6a8a6a308def8c9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f72656765782e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/regex)[![Tests](https://github.com/spatie/regex/workflows/Tests/badge.svg)](https://github.com/spatie/regex/workflows/Tests/badge.svg)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Total Downloads](https://camo.githubusercontent.com/960b716e232edf3feba27f3ecb1c8a4132562c4b10a13305c8afaa55adfbdf8b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f72656765782e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/regex)

Php's built in `preg_*` functions require some odd patterns like passing variables by reference and treating `false` or `null` values as errors. `spatie/regex` provides a cleaner interface for `preg_match`, `preg_match_all`, `preg_replace` and `preg_replace_callback`.

```
use Spatie\Regex\Regex;

// Using `match`
Regex::match('/a/', 'abc'); // `MatchResult` object
Regex::match('/a/', 'abc')->hasMatch(); // true
Regex::match('/a/', 'abc')->result(); // 'a'

// Capturing groups with `match`
Regex::match('/a(b)/', 'abc')->result(); // 'ab'
Regex::match('/a(b)/', 'abc')->group(1); // 'b'

// Setting defaults
Regex::match('/a(b)/', 'xyz')->resultOr('default'); // 'default'
Regex::match('/a(b)/', 'xyz')->groupOr(1, 'default'); // 'default'

// Using `matchAll`
Regex::matchAll('/a/', 'abcabc')->hasMatch(); // true
Regex::matchAll('/a/', 'abcabc')->results(); // Array of `MatchResult` objects

// Using replace
Regex::replace('/a/', 'b', 'abc')->result(); // 'bbc';
Regex::replace('/a/', function (MatchResult $result) {
    return $result->result() . 'Hello!';
}, 'abc')->result(); // 'aHello!bc';
```

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/bb98a31e9815aeaaf9907d9b9e3d7657902002eb1d86543e9808f0b0fca0d4c7/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f72656765782e6a70673f743d31)](https://spatie.be/github-ad-click/regex)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

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

[](#installation)

You can install the package via composer:

```
composer require spatie/regex
```

Usage
-----

[](#usage)

### Matching a pattern once

[](#matching-a-pattern-once)

Matches a pattern on a subject. Returns a `MatchResult` object for the first match.

```
/**
 * @param string $pattern
 * @param string $subject
 *
 * @return \Spatie\Regex\MatchResult
 */
Regex::match(string $pattern, string $subject): MatchResult
```

#### `MatchResult::hasMatch(): bool`

[](#matchresulthasmatch-bool)

Checks if the pattern matches the subject.

```
Regex::match('/abc/', 'abc')->hasMatch(); // true
Regex::match('/def/', 'abc')->hasMatch(); // false
```

#### `MatchResult::result(): string`

[](#matchresultresult-string)

Return the full match that was made. Returns `null` if no match was made.

```
Regex::match('/abc/', 'abc')->result(); // 'abc'
Regex::match('/def/', 'abc')->result(); // null
```

#### `MatchResult::group(int $id): string`

[](#matchresultgroupint-id-string)

Return the contents of a captured group (with a 1-based index). Throws a `RegexFailed` exception if the group doesn't exist.

```
Regex::match('/a(b)c/', 'abc')->group(1); // 'b'
Regex::match('/a(b)c/', 'abc')->group(2); // `RegexFailed` exception
```

### Matching all occurences of a pattern

[](#matching-all-occurences-of-a-pattern)

Matches a pattern on a subject. Returns a `MatchAllResult` object containing all matches.

```
/**
 * @param string $pattern
 * @param string $subject
 *
 * @return \Spatie\Regex\MatchAllResult
 */
public static function matchAll(string $pattern, string $subject): MatchAllResult
```

#### `MatchAllResult::hasMatch(): bool`

[](#matchallresulthasmatch-bool)

Checks if the pattern matches the subject.

```
Regex::matchAll('/abc/', 'abc')->hasMatch(); // true
Regex::matchAll('/abc/', 'abcabc')->hasMatch(); // true
Regex::matchAll('/def/', 'abc')->hasMatch(); // false
```

#### `MatchAllResult::results(): array`

[](#matchallresultresults-array)

Returns an array of `MatchResult` objects.

```
$results = Regex::matchAll('/ab([a-z])/', 'abcabd')->results();

$results[0]->result(); // 'abc'
$results[0]->group(1); // 'c'
$results[1]->result(); // 'abd'
$results[1]->group(1); // 'd'
```

### Replacing a pattern in a subject

[](#replacing-a-pattern-in-a-subject)

Replaces a pattern in a subject. Returns a `ReplaceResult` object.

```
/**
 * @param string|array $pattern
 * @param string|array|callable $replacement
 * @param string|array $subject
 * @param int $limit
 *
 * @return \Spatie\Regex\ReplaceResult
 */
public static function replace($pattern, $replacement, $subject, $limit = -1): ReplaceResult
```

#### `ReplaceResult::result(): mixed`

[](#replaceresultresult-mixed)

```
Regex::replace('/a/', 'b', 'abc')->result(); // 'bbc'
```

`Regex::replace` also works with callables. The callable will receive a `MatchResult` instance as it's argument.

```
Regex::replace('/a/', function (MatchResult $matchResult) {
    return str_repeat($matchResult->result(), 2);
}, 'abc')->result(); // 'aabc'
```

Patterns, replacements and subjects can also be arrays. `Regex::replace` behaves exactly like [`preg_replace`](http://php.net/manual/en/function.preg-replace.php) in those instances.

### Error handling

[](#error-handling)

If anything goes wrong in a `Regex` method, a `RegexFailed` exception gets thrown. No need for checking `preg_last_error()`.

Testing
-------

[](#testing)

```
$ composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

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

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Postcardware
------------

[](#postcardware)

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Sebastian De Deyne](https://github.com/sebastiandedeyne)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

65

—

FairBetter than 99% of packages

Maintenance54

Moderate activity, may be stable

Popularity71

Solid adoption and visibility

Community43

Growing community involvement

Maturity80

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~128 days

Recently: every ~61 days

Total

16

Last Release

1630d ago

Major Versions

0.1.0 → 1.0.02016-08-18

1.4.2 → 2.0.02021-03-31

2.0.1 → 3.0.02021-10-06

PHP version history (4 changes)0.0.1PHP ^7.0

1.4.2PHP ^7.3|^8.0

2.0.0PHP ^8.0

3.1.0PHP ^8.0|^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (56 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (18 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (8 commits)")[![riasvdv](https://avatars.githubusercontent.com/u/3626559?v=4)](https://github.com/riasvdv "riasvdv (5 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (3 commits)")[![Seldaek](https://avatars.githubusercontent.com/u/183678?v=4)](https://github.com/Seldaek "Seldaek (3 commits)")[![gpressutto5](https://avatars.githubusercontent.com/u/12385501?v=4)](https://github.com/gpressutto5 "gpressutto5 (3 commits)")[![pippinsmith](https://avatars.githubusercontent.com/u/48808207?v=4)](https://github.com/pippinsmith "pippinsmith (2 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (2 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (2 commits)")[![staabm](https://avatars.githubusercontent.com/u/120441?v=4)](https://github.com/staabm "staabm (2 commits)")[![Nathanael-Shermett](https://avatars.githubusercontent.com/u/33186878?v=4)](https://github.com/Nathanael-Shermett "Nathanael-Shermett (2 commits)")[![xeno010](https://avatars.githubusercontent.com/u/5448179?v=4)](https://github.com/xeno010 "xeno010 (1 commits)")[![carusogabriel](https://avatars.githubusercontent.com/u/16328050?v=4)](https://github.com/carusogabriel "carusogabriel (1 commits)")[![chapeupreto](https://avatars.githubusercontent.com/u/834048?v=4)](https://github.com/chapeupreto "chapeupreto (1 commits)")[![cochondeguerre](https://avatars.githubusercontent.com/u/272151221?v=4)](https://github.com/cochondeguerre "cochondeguerre (1 commits)")[![cv21](https://avatars.githubusercontent.com/u/4151152?v=4)](https://github.com/cv21 "cv21 (1 commits)")[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (1 commits)")[![introwit](https://avatars.githubusercontent.com/u/11228182?v=4)](https://github.com/introwit "introwit (1 commits)")

---

Tags

hacktoberfestphpregexregular-expressionspatieexpressionregexregularexpressions

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[composer/pcre

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

699313.8M34](/packages/composer-pcre)[spatie/laravel-package-tools

Tools for creating Laravel packages

945125.5M7.0k](/packages/spatie-laravel-package-tools)[spatie/laravel-data

Create unified resources and data transfer objects

1.8k28.9M627](/packages/spatie-laravel-data)[spatie/macroable

A trait to dynamically add methods to a class

72759.6M64](/packages/spatie-macroable)[spatie/enum

PHP Enums

84529.1M68](/packages/spatie-enum)[spatie/url

Parse, build and manipulate URL's

73914.3M97](/packages/spatie-url)

PHPackages © 2026

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