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.
Pros:
preg_match, preg_replace boilerplate) in validation, parsing, and text processing—areas where Laravel applications (e.g., form validation, API payload parsing, logging) frequently rely on regex.Cons:
preg_* calls, requiring refactoring effort to adopt the new API.preg_* calls for critical paths (e.g., high-volume API payload parsing).preg_* to the new API? (e.g., search/replace + tests, or gradual replacement?)preg_* for performance-critical paths?Rule classes for regex-based validation (e.g., custom RegexRule).AuthorizesRequests or ValidatesRequests.@regex) for client-side-like pattern matching in templates.Collection macro for regex operations (e.g., collect($strings)->extract('pattern')).Phase 1: Proof of Concept
// Before
if (preg_match('/^[A-Za-z0-9]+$/', $input)) { ... }
// After
if (Regex::test('/^[A-Za-z0-9]+$/', $input)) { ... }
Phase 2: Standardize API
RegexHelper) to encapsulate the package’s API and add Laravel-specific sugar (e.g., integration with validation errors).use PHPStandardLibrary\Regex;
use Illuminate\Validation\Rule;
class RegexRule extends Rule {
public function __construct(string $pattern) {
$this->pattern = $pattern;
}
public function passes($attribute, $value) {
return Regex::test($this->pattern, $value);
}
}
laravel-regex-helpers) for broader reuse.Phase 3: Gradual Replacement
preg_* calls and prioritize refactoring.u modifier) correctly for internationalized text.| Priority | Component | Integration Strategy | Risks |
|---|---|---|---|
| High | Validation Rules | Replace preg_match in custom rules. |
Breaking changes in validation. |
| Medium | API Request Parsing | Use in FormRequest or middleware. |
Payload format assumptions. |
| Medium | Blade Directives | Create @regex or @extract directives. |
Template performance. |
| Low | Logging/Background Jobs | Replace preg_replace in log processors. |
Low impact, test thoroughly. |
| Low | Unit Tests | Update regex-based assertions. | False negatives in tests. |
preg_* calls mean less maintenance overhead for regex logic.preg_* errors (e.g., uninitialized capture groups).bool for test(), structured arrays for extract()) reduce support tickets for edge cases.ValidationException).preg_* calls.| Scenario | Impact | Mitigation Strategy |
|---|---|---|
| Invalid Regex Pattern | RegexException (if wrapped). |
Fallback to raw preg_last_error() or log warnings. |
| PC |
How can I help you explore Laravel packages today?