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.
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
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']
]);
replace() for conditional or dynamic replacements:
$result = Regex::replace('/\$(\d+)/', 'Price is $100', function ($amount) {
return '€' . $amount[1] * 0.92;
});
// → 'Price is €100'
RegexResult methods:->isSuccessful(), ->match($index), ->matches(), ->groups() — avoid raw array access and undefined index errors.'\/path\/to\/file' → safer: '#path/to/file#'.Regex::compile() or use native preg_* where performance is critical.pcre.jit=1 in php.ini. Without it, patterns with heavy backtracking (e.g., nested quantifiers) may timeout or OOM.@ silencing: Unlike raw preg_*, this package throws Spatie\Regex\InvalidRegex on malformed patterns — handle appropriately (e.g., validate user input patterns).(?<name>...)) for readability, and use ->groups() instead of ->match(1), which is brittle if pattern order changes.How can I help you explore Laravel packages today?