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

Regexp Builder Laravel Package

s9e/regexp-builder

Generate compact regular expressions that match a given list of strings (ideal for keyword search). Builds optimized patterns like ba[rz]|foo from input terms, with factories for PHP, Java, JavaScript, RE2, plus RawBytes/RawUTF8 output modes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require s9e/regexp-builder
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Generate a regex to match a predefined list of strings (e.g., usernames, keywords, or validation rules):

    use S9e\Regexp\Builder;
    
    $builder = new Builder();
    $regex = $builder->addStrings(['apple', 'banana', 'cherry'])->getRegex();
    // Output: `^(?:apple|banana|cherry)$`
    
  3. Where to Look First:

    • README for core concepts (e.g., addString(), addPattern(), getRegex()).
    • API Docs for advanced options like flags (caseInsensitive(), multiline()), anchors, or quantifiers.

Implementation Patterns

Core Workflows

  1. String Matching: Dynamically build regexes for input validation or filtering:

    $builder = new Builder();
    $builder->addStrings(['admin', 'moderator', 'user'])
            ->anchorStart()
            ->anchorEnd();
    $regex = $builder->getRegex(); // `^admin|moderator|user$`
    
  2. Pattern Reuse: Combine static patterns with dynamic strings:

    $builder = new Builder();
    $builder->addPattern('^https?://') // Prefix
            ->addStrings(['example.com', 'google.com'])
            ->addPattern('/.*$'); // Suffix
    
  3. Laravel Integration:

    • Validation Rules:
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make($request->all(), [
          'username' => ['required', function ($attribute, $value, $fail) {
              $regex = (new Builder())->addStrings(['admin', 'root'])->getRegex();
              if (preg_match($regex, $value)) {
                  $fail('Username restricted.');
              }
          }]
      ]);
      
    • Route Model Binding: Use regex-generated patterns to filter dynamic routes (e.g., Route::where('slug', $regex)).
  4. Caching Compiled Regexes: Store generated regexes in Laravel’s cache for performance:

    $cacheKey = 'regex_user_roles';
    $regex = Cache::remember($cacheKey, now()->addHours(1), function () {
        return (new Builder())->addStrings(['editor', 'author'])->getRegex();
    });
    

Advanced Patterns

  • Character Classes:
    $builder->addString('a1')->addString('b2')->addCharacterClass('digit');
    // Output: `[a-b][0-9]`
    
  • Quantifiers:
    $builder->addString('abc')->addString('abcd')->addString('abcde')
            ->addQuantifier('+'); // Matches 1+ occurrences
    
  • Flags:
    $builder->addStrings(['Apple', 'Banana'])
            ->caseInsensitive()
            ->getRegex(); // `^(?:apple|banana)$` with `i` flag
    

Gotchas and Tips

Pitfalls

  1. Overly Complex Regexes:

    • Issue: Adding thousands of strings can bloat the regex (e.g., ^(?:str1|str2|...|str1000)$).
    • Fix: Use addCharacterClass() for similar strings or split into multiple builders.
  2. Anchors and Partial Matches:

    • Issue: Forgetting anchorStart()/anchorEnd() may allow unintended partial matches.
    • Fix: Default to anchoring unless full-string matching is unnecessary.
  3. Special Characters:

    • Issue: Strings with regex metacharacters (e.g., ., *) may break the pattern.
    • Fix: Use addString() (auto-escapes) or addPattern() for manual control.
  4. Performance:

    • Issue: Compiling regexes on-the-fly in loops can be slow.
    • Fix: Cache regexes or pre-generate them during bootstrapping.

Debugging Tips

  • Validate Regexes: Use PHP’s preg_last_error() to debug malformed regexes:
    $regex = $builder->getRegex();
    if (!preg_match($regex, 'test')) {
        echo 'Error: ' . preg_last_error();
    }
    
  • Inspect Intermediate Steps: Call getRegex() after each add* method to verify incremental builds:
    $builder->addString('test');
    echo $builder->getRegex(); // `test`
    $builder->anchorStart();
    echo $builder->getRegex(); // `^test`
    

Extension Points

  1. Custom Escaping: Override escaping logic for non-standard strings:

    $builder->setStringEscaper(function ($str) {
        return preg_quote($str, '/');
    });
    
  2. Post-Processing: Modify the final regex with a callback:

    $regex = $builder->getRegex();
    $regex = preg_replace('/\|/', '|', $regex); // Example tweak
    
  3. Laravel Service Provider: Bind the builder to the container for dependency injection:

    $this->app->singleton(Builder::class, function () {
        return new Builder();
    });
    
  4. Testing: Use Laravel’s Assert to validate regex behavior:

    $this->assertMatchesRegularExpression(
        (new Builder())->addStrings(['foo', 'bar'])->getRegex(),
        'foo'
    );
    
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata