Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Regex Laravel Package

spatie/regex

Cleaner, safer wrapper around PHP’s preg_* functions. Provides Regex::match/matchAll/replace with MatchResult objects, easy access to groups, sensible defaults, and callback-based replacements—no by-reference variables or confusing false/null error handling.

View on GitHub
Deep Wiki
Context7

Getting Started

Start by installing via Composer: composer require spatie/regex. This package wraps PHP’s native preg_* functions with a cleaner, exception-handling, and more intuitive API. The primary class is Spatie\Regex\Regex, which offers static methods like match(), matchAll(), replace(), and test(). Begin with simple pattern matching:

use Spatie\Regex\Regex;

$result = Regex::match('/foo/', 'foobar'); // Returns ['foo']
if ($result->isSuccessful()) {
    echo $result->match(0); // 'foo'
}

Use the test() method for quick boolean checks:

Regex::test('/\d+/', 'Version 1.2'); // true

Implementation Patterns

  • Parsing structured strings: Extract segments with named groups using matchAll():
    $matches = Regex::matchAll('/(?<date>\d{4}-\d{2}-\d{2}) (?<time>\d{2}:\d{2})/', '2023-04-01 15:30');
    $matches->map(fn ($match) => [
        'date' => $match['date'],
        'time' => $match['time']
    ]);
    
  • Replacing with callbacks: Use replace() for conditional or dynamic replacements:
    $result = Regex::replace('/\$(\d+)/', 'Price is $100', function ($amount) {
        return '€' . $amount[1] * 0.92;
    });
    // → 'Price is €100'
    
  • Type-safe workflows: Chain operations with RegexResult methods:
    ->isSuccessful(), ->match($index), ->matches(), ->groups() — avoid raw array access and undefined index errors.

Gotchas and Tips

  • Backslashes in patterns: PHP string interpolation can mangle regex — always use single quotes or escape slashes: '\/path\/to\/file' → safer: '#path/to/file#'.
  • Performance: While convenient, each static call instantiates internal state. For tight loops, cache compiled patterns via Regex::compile() or use native preg_* where performance is critical.
  • No PCRE JIT by default: PHP’s JIT requires pcre.jit=1 in php.ini. Without it, patterns with heavy backtracking (e.g., nested quantifiers) may timeout or OOM.
  • Exceptions vs. @ silencing: Unlike raw preg_*, this package throws Spatie\Regex\InvalidRegex on malformed patterns — handle appropriately (e.g., validate user input patterns).
  • Named groups vs numeric indices: Prefer named groups ((?<name>...)) for readability, and use ->groups() instead of ->match(1), which is brittle if pattern order changes.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport