php-standard-library/regex
Type-safe regex for PHP with typed capture groups and predictable error handling. Build expressions with confidence, get structured match results, and avoid silent failures common in preg_* functions. Part of PHP Standard Library.
Installation
composer require php-standard-library/regex
No configuration required—just autoload.
First Use Case: Basic Matching
use PhpStandardLibrary\Regex\Regex;
$regex = new Regex('/\d{3}-\d{2}-\d{4}/'); // SSN pattern
$matches = $regex->match('123-45-6789'); // Returns array of matches or null
Where to Look First
PhpStandardLibrary\Regex\Regex (main entry point).match() → Capture groups.test() → Boolean check.replace() → Substring replacement.extract() → Multi-match extraction.src/Regex.php for method signatures and examples.Replace repetitive preg_match() calls with a cleaner API:
$regex = new Regex('/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/');
if ($regex->test($email)) {
// Valid email
}
Extract multiple matches into an array (e.g., parsing logs or CSV):
$regex = new Regex('/(\d{2})\/(\d{2})\/(\d{4})/');
$dates = $regex->extract('01/15/2023, 02/20/2024');
// Returns: [['01', '15', '2023'], ['02', '20', '2024']]
Avoid preg_replace() errors with built-in safety:
$regex = new Regex('/\b\w{1,3}\b/'); // Short words
$text = $regex->replace('Hello world!', '*');
// "He*o wor*!"
use PhpStandardLibrary\Regex\Regex;
public function rules()
{
return [
'phone' => ['regex:/^\+?[0-9]{10,15}$/'],
];
}
class PhoneValidator {
public function __construct(private Regex $regex) {}
public function isValid(string $phone): bool
{
return $this->regex->test('/^\+?[0-9]{10,15}$/', $phone);
}
}
Mock Regex in unit tests for predictable behavior:
$regex = $this->createMock(Regex::class);
$regex->method('test')->willReturn(true);
Pattern Compilation Errors
preg_*, this library throws exceptions on invalid patterns (e.g., unclosed ().try-catch or validate patterns first:
try {
$regex = new Regex('/invalid[pattern/');
} catch (RegexException $e) {
Log::error($e->getMessage());
}
Case Sensitivity
$regex = new Regex('/pattern/i'); // Case-insensitive
Performance with Large Texts
$regex = new Regex('/pattern/', Regex::PRE_COMPILE);
$regex->match('text', Regex::DEBUG); // Returns matches + debug info
Regex::getPattern() to verify the active pattern during debugging.Custom Modifiers Extend the class to add domain-specific modifiers:
class CustomRegex extends Regex {
public function __construct(string $pattern, string $customModifier = '') {
parent::__construct($pattern, ['custom' => $customModifier]);
}
}
Integration with Laravel Collectors
Chain regex operations with Laravel’s Collection:
$emails = collect($users)->map(fn ($user) => $user->email)
->filter(fn ($email) => (new Regex('/@gmail\.com$/'))->test($email));
Reusable Pattern Library
Store patterns in a config file (e.g., config/regex.php) and instantiate dynamically:
$pattern = config('regex.email');
$regex = new Regex($pattern);
$this->app->singleton(Regex::class, fn () => new Regex('', ['DEFAULT_FLAG' => 'u']));
How can I help you explore Laravel packages today?