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

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/regex
    

    No configuration required—just autoload.

  2. 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
    
  3. Where to Look First

    • Core Class: PhpStandardLibrary\Regex\Regex (main entry point).
    • Key Methods:
      • match() → Capture groups.
      • test() → Boolean check.
      • replace() → Substring replacement.
      • extract() → Multi-match extraction.
    • Documentation: Check src/Regex.php for method signatures and examples.

Implementation Patterns

1. Fluent Validation Workflows

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
}

2. Structured Data Extraction

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']]

3. Safe Replacements

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*!"

4. Integration with Laravel

  • Form Request Validation:
    use PhpStandardLibrary\Regex\Regex;
    
    public function rules()
    {
        return [
            'phone' => ['regex:/^\+?[0-9]{10,15}$/'],
        ];
    }
    
  • Service Layer:
    class PhoneValidator {
        public function __construct(private Regex $regex) {}
    
        public function isValid(string $phone): bool
        {
            return $this->regex->test('/^\+?[0-9]{10,15}$/', $phone);
        }
    }
    

5. Testing

Mock Regex in unit tests for predictable behavior:

$regex = $this->createMock(Regex::class);
$regex->method('test')->willReturn(true);

Gotchas and Tips

Pitfalls

  1. Pattern Compilation Errors

    • Unlike preg_*, this library throws exceptions on invalid patterns (e.g., unclosed ().
    • Fix: Wrap in a try-catch or validate patterns first:
      try {
          $regex = new Regex('/invalid[pattern/');
      } catch (RegexException $e) {
          Log::error($e->getMessage());
      }
      
  2. Case Sensitivity

    • Defaults to case-sensitive matching. Use modifiers explicitly:
      $regex = new Regex('/pattern/i'); // Case-insensitive
      
  3. Performance with Large Texts

    • For heavy processing (e.g., parsing logs), pre-compile patterns:
      $regex = new Regex('/pattern/', Regex::PRE_COMPILE);
      

Debugging Tips

  • Inspect Matches:
    $regex->match('text', Regex::DEBUG); // Returns matches + debug info
    
  • Log Patterns: Use Regex::getPattern() to verify the active pattern during debugging.

Extension Points

  1. 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]);
        }
    }
    
  2. 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));
    
  3. 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);
    

Config Quirks

  • No Global Config: The library is stateless—patterns are passed per instance.
  • Default Flags: Override globally via a service provider:
    $this->app->singleton(Regex::class, fn () => new Regex('', ['DEFAULT_FLAG' => 'u']));
    
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