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

Reverse Regex Laravel Package

ilario-pierbattista/reverse-regex

Generate example strings from regular expressions in PHP—useful for test data for forms, databases, and regex validation. Includes lexer/parser and random generators, supports literals, groups, classes, ranges, and quantifiers (with some Unicode/PCRE limits).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ilario-pierbattista/reverse-regex
    

    Ensure your project uses PHP 8.1+ (hard requirement).

  2. Basic Usage:

    use ReverseRegex\Lexer;
    use ReverseRegex\Random\SimpleRandom;
    use ReverseRegex\Parser;
    use ReverseRegex\Generator\Scope;
    
    $lexer = new Lexer('[A-Za-z0-9]{10}');
    $generator = new SimpleRandom(12345); // Seed for reproducibility
    $parser = new Parser($lexer, new Scope(), new Scope());
    
    $result = $parser->parse()->getResult()->generate('', $generator);
    // Output: e.g., "aB3dE7fG9h"
    
  3. First Use Case: Generate test data for Laravel validation rules. For example, if your User model validates phone_number with regex /^04\d{8}$/, use:

    $phoneRegex = '04\d{8}';
    $phoneNumber = (new Parser(new Lexer($phoneRegex), new Scope(), new Scope()))
        ->parse()
        ->getResult()
        ->generate('', new SimpleRandom());
    // Output: e.g., "0412345678"
    

Where to Look First

  • Examples: Study the provided examples (e.g., ausphone.php, auspostcode.php) for real-world Laravel use cases.
  • Regex Support Table: Reference the README’s table to confirm your patterns are compatible.
  • Changelog: Check 0.6.0 for PHPStan and CI/CD integration notes.

Implementation Patterns

Core Workflow

  1. Define Regex: Store validation regexes in a config file (e.g., config/test_data.php) or as constants:

    // config/test_data.php
    return [
        'phone' => '04\d{8}',
        'postcode' => '\d{4}',
        'username' => '[a-z0-9_]{8,20}',
    ];
    
  2. Create a Test Helper: Wrap the package in a Laravel service or helper:

    // app/Helpers/RegexGenerator.php
    namespace App\Helpers;
    
    use ReverseRegex\Lexer;
    use ReverseRegex\Parser;
    use ReverseRegex\Generator\Scope;
    use ReverseRegex\Random\SimpleRandom;
    
    class RegexGenerator
    {
        public static function generate(string $regex, int $seed = null): string
        {
            $lexer = new Lexer($regex);
            $generator = new SimpleRandom($seed ?? random_int(0, PHP_INT_MAX));
            return (new Parser($lexer, new Scope(), new Scope()))
                ->parse()
                ->getResult()
                ->generate('', $generator);
        }
    }
    
  3. Integrate with Laravel Testing:

    • PestPHP:
      use App\Helpers\RegexGenerator;
      
      test('phone number validation', function () {
          $phone = RegexGenerator::generate('04\d{8}');
          $this->assertMatchesRegularExpression('/^04\d{8}$/', $phone);
      });
      
    • PHPUnit:
      use App\Helpers\RegexGenerator;
      
      public function testPostcodeValidation()
      {
          $postcode = RegexGenerator::generate('\d{4}');
          $this->assertMatchesRegularExpression('/^\d{4}$/', $postcode);
      }
      
  4. Database Seeding: Use in DatabaseSeeder or model factories:

    // database/seeders/DatabaseSeeder.php
    public function run()
    {
        User::factory()->count(10)->create()->each(function ($user) {
            $user->phone_number = RegexGenerator::generate('04\d{8}');
            $user->save();
        });
    }
    

Advanced Patterns

  1. Seeded Randomness: Use a fixed seed for reproducible tests:

    $seededGenerator = new SimpleRandom(42);
    $result = $parser->parse()->getResult()->generate('', $seededGenerator);
    
  2. Unicode Support: Generate emojis or special characters:

    $emojiRegex = '\X{1F600}-\X{1F64F}'; // Unicode range for smiling faces
    $emoji = RegexGenerator::generate($emojiRegex);
    
  3. Complex Regex: Handle nested groups and alternations:

    $complexRegex = '(abc|def){3}'; // Generates "abcabcabc" or "defdefdef"
    $output = RegexGenerator::generate($complexRegex);
    
  4. Integration with Faker: Combine with Faker for hybrid test data:

    use Faker\Factory as Faker;
    
    $faker = Faker::create();
    $email = $faker->unique()->email;
    $password = RegexGenerator::generate('[a-zA-Z0-9]{12}');
    
  5. Custom Random Generators: Extend SimpleRandom for domain-specific logic:

    class DomainRandom extends SimpleRandom
    {
        protected function generateCharacter(): string
        {
            // Custom logic for business-specific rules
            return parent::generateCharacter();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Unsupported Regex Features:

    • Avoid: \p{L} (Unicode properties), lookarounds, backreferences, or conditional regex.
    • Workaround: Pre-process regexes to remove unsupported features or use simpler patterns.
  2. Quantifier Behavior:

    • * and + can generate extremely long strings (up to PHP_INT_MAX). Use explicit ranges (e.g., {1,10}) for control.
    • Fix: Limit quantifiers in your regex or handle overflow in the generator.
  3. Escaping Meta-Characters:

    • Always escape regex meta-characters (e.g., \., \*) before passing to Lexer.
    • Tip: Use preg_quote() for dynamic regexes:
      $safeRegex = preg_quote($userInput, '/');
      
  4. PHP 8.1+ Requirement:

    • Error: Attempting to use on PHP 7.4/8.0 will fail.
    • Fix: Upgrade or fork the package to support older versions.
  5. Unicode Limitations:

    • \p{...} (Unicode properties) are not supported. Use \X{####} for codepoints.
    • Workaround: Manually map Unicode ranges or use hex notation (\xFF).
  6. Performance with Large Quantifiers:

    • Generating strings with {1,1000} can be slow. Optimize by:
      • Using smaller ranges.
      • Pre-generating and caching common patterns.

Debugging Tips

  1. Validate Regex First: Test your regex with preg_match() before using ReverseRegex:

    $regex = '[a-z]{5}';
    $testString = 'abcde';
    $this->assertTrue(preg_match("/{$regex}/", $testString));
    
  2. Check Parser Output: Inspect the parsed AST for debugging:

    $parsed = $parser->parse();
    dump($parsed->getResult()->getStructure());
    
  3. Handle Edge Cases:

    • Empty results: Ensure your regex has at least one possible match.
    • Infinite loops: Avoid recursive patterns or unbounded quantifiers.
  4. CI/CD Integration:

    • Run composer phpstan and composer cs-check in your pipeline to enforce standards.
    • Fix: Address PHPStan errors by updating your code or the package (consider contributing fixes).

Extension Points

  1. Custom Generators: Extend SimpleRandom to implement domain-specific logic:

    class BusinessRandom extends SimpleRandom
    {
        protected function generateCharacter(): string
        {
            // Example: Only allow vowels for certain fields
            return $this->randomElement(['a', 'e', 'i', 'o', 'u']);
        }
    }
    
  2. Laravel Service Provider: Bind the generator to the container for global access:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(RegexGenerator::class, function ($app) {
            return new RegexGenerator();
        });
    }
    
  3. PestPHP Custom Macro: Add a macro to Pest for seamless integration:

    // tests/Pest.php
    use App\Helpers\RegexGenerator;
    
    Pest::macro('regex', function ($pattern) {
        return Regex
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai