Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Spatie Regex
https://github.com/spatie/regex
Admin
Spatie Regex is a PHP package that provides a cleaner, more expressive interface for working with
...
Tokens:
5,002
Snippets:
32
Trust Score:
8.5
Update:
3 weeks ago
Context
Skills
Chat
Benchmark
96.5
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Spatie Regex Spatie Regex is a PHP library that provides a clean, expressive interface for working with regular expressions. It wraps PHP's native `preg_*` functions (`preg_match`, `preg_match_all`, `preg_replace`, and `preg_replace_callback`) and eliminates common pain points like passing variables by reference, handling `false`/`null` returns, and checking `preg_last_error()`. The library offers three main operations: `match()` for finding a single match, `matchAll()` for finding all occurrences, and `replace()` for pattern-based string replacements. Each method returns a strongly-typed result object (`MatchResult`, `MatchAllResult`, or `ReplaceResult`) with intuitive methods for accessing match data, captured groups, and handling defaults. When errors occur, the library throws descriptive `RegexFailed` exceptions instead of returning cryptic error codes. ## Installation ```bash composer require spatie/regex ``` ## Regex::match - Single Pattern Matching The `match()` method executes a regex pattern against a subject string and returns a `MatchResult` object representing the first match found. It provides methods to check if a match exists, retrieve the full match, and access captured groups by index or name. ```php use Spatie\Regex\Regex; use Spatie\Regex\Exceptions\RegexFailed; // Basic pattern matching $result = Regex::match('/abc/', 'abcdef'); $result->hasMatch(); // true $result->result(); // 'abc' // No match returns null for result $result = Regex::match('/xyz/', 'abcdef'); $result->hasMatch(); // false $result->result(); // null // Capturing groups (1-based index) $result = Regex::match('/a(b)(c)/', 'abcdef'); $result->result(); // 'abc' (full match) $result->group(1); // 'b' $result->group(2); // 'c' // Named capturing groups $result = Regex::match('/(?<first>\w+)@(?<domain>\w+\.\w+)/', 'user@example.com'); $result->result(); // 'user@example.com' $result->group('first'); // 'user' $result->namedGroup('domain'); // 'example.com' // Get all groups as array $result = Regex::match('/(a)(b)(c)/', 'abc'); $result->groups(); // ['abc', 'a', 'b', 'c'] // Default values for missing matches $result = Regex::match('/blue/', 'yellow'); $result->resultOr('default'); // 'default' $result = Regex::match('/the sky is (.+)/', 'unknown text'); $result->groupOr(1, 'blue'); // 'blue' // Unmatched optional groups return null $result = Regex::match('/(?<A>a)|(?<B>b)/', 'a'); $groups = $result->groups(); $groups['A']; // 'a' $groups['B']; // null // Exception handling for non-existent groups try { Regex::match('/(a)bc/', 'abcdef')->group(5); } catch (RegexFailed $e) { echo $e->getMessage(); // "Pattern `/(a)bc/` with subject `abcdef` didn't capture a group named 5" } // Exception for invalid patterns try { Regex::match('/abc', 'abc'); // Missing closing delimiter } catch (RegexFailed $e) { echo $e->getMessage(); // "Error matching pattern `/abc` with subject `abc`. preg_match(): No ending delimiter '/' found" } ``` ## Regex::matchAll - Multiple Pattern Matching The `matchAll()` method finds all occurrences of a pattern in a subject string and returns a `MatchAllResult` object. The `results()` method returns an array of `MatchResult` objects, each with access to the full match and captured groups. ```php use Spatie\Regex\Regex; // Find all occurrences $result = Regex::matchAll('/a/', 'banana'); $result->hasMatch(); // true $matches = $result->results(); count($matches); // 3 $matches[0]->result(); // 'a' $matches[1]->result(); // 'a' $matches[2]->result(); // 'a' // No matches returns empty array $result = Regex::matchAll('/xyz/', 'abcdef'); $result->hasMatch(); // false $result->results(); // [] // Capturing groups in multiple matches $result = Regex::matchAll('/a(b)/', 'ababab'); $matches = $result->results(); count($matches); // 3 $matches[0]->result(); // 'ab' $matches[0]->group(1); // 'b' $matches[1]->result(); // 'ab' $matches[1]->group(1); // 'b' // Named groups with matchAll $text = <<<'TEXT' the sky is blue foo bar the sky is green the sky is red TEXT; $result = Regex::matchAll('/the sky is (?<color>.+)/', $text); $matches = $result->results(); count($matches); // 3 $matches[0]->result(); // 'the sky is blue' $matches[0]->group('color'); // 'blue' $matches[0]->group(1); // 'blue' $matches[1]->group('color'); // 'green' $matches[2]->group('color'); // 'red' // Extract all email addresses from text $text = 'Contact us at support@example.com or sales@company.org for more info.'; $result = Regex::matchAll('/[\w.+-]+@[\w-]+\.[\w.-]+/', $text); foreach ($result->results() as $match) { echo $match->result() . "\n"; } // Output: // support@example.com // sales@company.org ``` ## Regex::replace - Pattern Replacement The `replace()` method performs pattern-based string replacement and returns a `ReplaceResult` object. It supports string replacements, callback replacements (receiving `MatchResult` objects), array patterns, and replacement limits. ```php use Spatie\Regex\Regex; use Spatie\Regex\MatchResult; // Simple string replacement $result = Regex::replace('/a/', 'b', 'aabb'); $result->result(); // 'bbbb' $result->count(); // 2 (number of replacements made) // Callback replacement with MatchResult $result = Regex::replace('/a(b)/', function (MatchResult $match) { return strtoupper($match->result()); }, 'abc'); $result->result(); // 'ABc' // Callback with access to captured groups $result = Regex::replace('/(\w+)@(\w+)\.(\w+)/', function (MatchResult $match) { $user = $match->group(1); $domain = $match->group(2); return "{$user} at {$domain}"; }, 'Email: user@example.com'); $result->result(); // 'Email: user at example' // Duplicate matched content $result = Regex::replace('/a/', function (MatchResult $match) { return $match->result() . $match->result(); }, 'abc'); $result->result(); // 'aabc' // Limit number of replacements $result = Regex::replace('/a/', 'b', 'aaaa', 2); $result->result(); // 'bbaa' $result->count(); // 2 // Array of patterns with single replacement $result = Regex::replace(['/a/', '/b/'], 'c', 'aabb'); $result->result(); // 'cccc' // Array of patterns with array of replacements $result = Regex::replace(['/a/', '/b/'], ['x', 'y'], 'aabb'); $result->result(); // 'xxyy' // Working with array subjects $subjects = ['apple', 'banana', 'apricot']; $result = Regex::replace('/a/', 'X', $subjects); $result->result(); // ['Xpple', 'bXnXnX', 'Xpricot'] // Practical example: Format phone numbers $result = Regex::replace( '/(\d{3})(\d{3})(\d{4})/', '($1) $2-$3', 'Call 5551234567 now!' ); $result->result(); // 'Call (555) 123-4567 now!' // Practical example: Slugify text $text = 'Hello World! This is a Test.'; $result = Regex::replace('/[^a-z0-9]+/i', '-', strtolower($text)); $result->result(); // 'hello-world-this-is-a-test-' ``` ## Error Handling with RegexFailed Exception The `RegexFailed` exception is thrown when regex operations fail, providing clear error messages that include the pattern, subject, and specific error details. This eliminates the need to check `preg_last_error()` manually. ```php use Spatie\Regex\Regex; use Spatie\Regex\Exceptions\RegexFailed; // Handle invalid pattern errors try { Regex::match('/[invalid/', 'subject'); } catch (RegexFailed $e) { echo $e->getMessage(); // "Error matching pattern `/[invalid/` with subject `subject`. ..." } // Handle catastrophic backtracking try { Regex::match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar'); } catch (RegexFailed $e) { echo $e->getMessage(); // "Error matching pattern `...` with subject `foobar foobar foobar`. Backtrack limit exhausted" } // Handle non-existent capture groups try { $result = Regex::match('/(a)/', 'abc'); $result->group(5); // Group 5 doesn't exist } catch (RegexFailed $e) { echo $e->getMessage(); // "Pattern `/(a)/` with subject `abc` didn't capture a group named 5" } // Safe group access with defaults (no exception) $result = Regex::match('/(a)/', 'abc'); $value = $result->groupOr(5, 'fallback'); // 'fallback' // Replacement error handling try { Regex::replace('/unclosed(group/', 'replacement', 'subject'); } catch (RegexFailed $e) { echo $e->getMessage(); // "Error replacing pattern `/unclosed(group/` in subject `subject`. ..." } // Long subjects are trimmed in error messages (40 chars max) try { $longSubject = str_repeat('a', 100); Regex::replace('/invalid', 'b', $longSubject); } catch (RegexFailed $e) { // Subject shown as: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa..." } ``` ## Summary Spatie Regex is ideal for PHP developers who work frequently with regular expressions and want cleaner, more readable code. Common use cases include form validation (email, phone, URLs), text parsing and extraction (log files, CSV data, HTML content), string transformation and sanitization, and building search functionality. The library's object-oriented approach with typed result objects makes it easy to chain operations and handle edge cases gracefully. Integration is straightforward via Composer, with no external dependencies beyond PHP 8.0+. The library follows PSR-4 autoloading standards and works seamlessly with any PHP framework or standalone application. For testing, the explicit exception-based error handling makes it easy to write assertions and mock regex operations. The consistent API across `match()`, `matchAll()`, and `replace()` means developers can quickly become productive without memorizing different parameter orders or return value conventions.