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 Steps

  1. Installation: Add the package via Composer in your Laravel project:

    composer require php-standard-library/regex
    

    Ensure your composer.json includes "php": "^8.0" (or higher) as a requirement.

  2. First Use Case: Replace a basic preg_match validation with the package’s type-safe alternative. For example:

    use PHPStandardLibrary\Regex;
    
    // Traditional approach
    if (preg_match('/^[A-Za-z0-9]+$/', $input)) {
        // Process valid input
    }
    
    // With the package
    if (Regex::test('/^[A-Za-z0-9]+$/', $input)) {
        // Process valid input
    }
    
  3. Key Entry Points:

    • Regex::test(string $pattern, string $subject): Equivalent to preg_match but returns a bool.
    • Regex::extract(string $pattern, string $subject): Returns an array of typed capture groups (e.g., ['group1' => string, 'group2' => int]).
    • Regex::replace(string $pattern, string $replacement, string $subject): Type-safe preg_replace.
  4. Where to Look First:

    • Documentation for API reference and examples.
    • src/Regex.php in the package source to understand the core methods and their return types.
    • Laravel’s Validator or FormRequest classes to integrate regex logic into validation rules.

Implementation Patterns

Usage Patterns

1. Validation Integration

Use the package to create reusable validation rules in Laravel. Example:

use PHPStandardLibrary\Regex;
use Illuminate\Validation\Rule;

class RegexRule extends Rule {
    protected $pattern;

    public function __construct(string $pattern) {
        $this->pattern = $pattern;
    }

    public function passes($attribute, $value) {
        return Regex::test($this->pattern, $value);
    }
}

// Usage in FormRequest
public function rules() {
    return [
        'username' => ['required', new RegexRule('/^[A-Za-z0-9_]{4,20}$/')],
    ];
}

2. Structured Data Extraction

Extract and type-cast capture groups from strings (e.g., parsing logs, CSV, or API responses):

$logLine = "2023-10-01 [ERROR] User 123 failed login";
$matches = Regex::extract(
    '/(\d{4}-\d{2}-\d{2}) \[([A-Z]+)\] User (\d+) (.+)/',
    $logLine
);

// $matches is typed as:
// [
//     'date' => '2023-10-01',
//     'level' => 'ERROR',
//     'userId' => '123',
//     'message' => 'failed login'
// ]

3. Text Transformation

Replace patterns with type safety (e.g., sanitizing user input or normalizing text):

$sanitized = Regex::replace(
    '/[^A-Za-z0-9\s]/', // Pattern
    '-',                // Replacement
    $userInput          // Subject
);

4. Laravel Collections Macro

Extend Laravel’s Collection to add regex methods:

use Illuminate\Support\Collection;

Collection::macro('extractRegex', function ($pattern) {
    return $this->map(function ($item) use ($pattern) {
        return Regex::extract($pattern, $item);
    });
});

// Usage
$logs = collect($logLines)->extractRegex('/\d{4}-\d{2}-\d{2}/');

5. Blade Directives

Create custom Blade directives for client-side-like regex operations:

use Illuminate\Support\Facades\Blade;

Blade::directive('regex', function ($expression) {
    return "<?php echo PHPStandardLibrary\Regex::test({$expression[0]}, {$expression[1]}); ?>";
});

// Usage in Blade
@regex('/^[A-Za-z]+$/', $username)
    <p>Username is valid!</p>
@else
    <p>Invalid username.</p>
@endregex

Workflows

Validation Workflow

  1. Define Patterns: Store regex patterns in a config file (e.g., config/regex.php) for reusability.
    return [
        'username' => '/^[A-Za-z0-9_]{4,20}$/',
        'email' => '/^[^\s@]+@[^\s@]+\.[^\s@]+$/',
    ];
    
  2. Create Rules: Dynamically instantiate RegexRule in FormRequest or Validator.
    $validator = Validator::make($request->all(), [
        'username' => ['required', new RegexRule(config('regex.username'))],
    ]);
    
  3. Handle Errors: Customize error messages in the rule or use Laravel’s built-in validation messages.

Parsing Workflow

  1. Extract Data: Use Regex::extract() to parse structured text (e.g., logs, CSV).
    $data = Regex::extract('/(\d+),([^,]+),(\d+\.\d+)/', $csvLine);
    
  2. Type-Cast Results: Leverage the package’s typed return values to avoid manual casting.
    $id = (int) $data['group1']; // Automatically cast to int if pattern enforces it
    
  3. Process Collections: Use the extractRegex macro to parse batches of data.
    $parsedData = $collection->extractRegex('/pattern/');
    

Testing Workflow

  1. Unit Tests: Test regex patterns in isolation.
    public function testUsernameValidation() {
        $this->assertTrue(Regex::test('/^[A-Za-z0-9_]{4,20}$/', 'valid_user'));
        $this->assertFalse(Regex::test('/^[A-Za-z0-9_]{4,20}$/', 'invalid user!'));
    }
    
  2. Integration Tests: Verify validation rules or parsing logic in feature tests.
    public function testFormRequestValidation() {
        $response = $this->post('/register', ['username' => 'bad@user']);
        $response->assertSessionHasErrors('username');
    }
    

Integration Tips

  1. Leverage Laravel’s Service Container: Bind the package to the container for dependency injection:

    $this->app->singleton('regex', function () {
        return new \PHPStandardLibrary\Regex();
    });
    

    Then inject it into classes:

    public function __construct(private Regex $regex) {}
    
  2. Custom Error Handling: Extend the package’s error handling to integrate with Laravel’s exception system:

    try {
        Regex::extract('/invalid_pattern/', $subject);
    } catch (\PHPStandardLibrary\Regex\RegexException $e) {
        throw new \Illuminate\Validation\ValidationException($e->getMessage());
    }
    
  3. Performance Optimization:

    • Pre-compile Patterns: Cache compiled regex patterns for repeated use (e.g., in validation rules).
      static private $compiledPatterns = [];
      
      public static function test(string $pattern, string $subject) {
          if (!isset(self::$compiledPatterns[$pattern])) {
              self::$compiledPatterns[$pattern] = preg_compile($pattern);
          }
          return preg_match(self::$compiledPatterns[$pattern], $subject);
      }
      
    • Benchmark: Compare performance against raw preg_* for critical paths using Laravel’s Benchmark facade.
  4. Documentation:

    • Add PHPDoc annotations to custom methods using the package to clarify expected patterns and return types.
      /**
       * Validates a username using a predefined regex pattern.
       *
       * @param string $username The username to validate.
       * @return bool True if the username matches /^[A-Za-z0-9_]{4,20}$/.
       */
      public function validateUsername(string $username): bool {
          return Regex::test('/^[A-Za-z0-9_]{4,20}$/', $username);
      }
      
  5. Team Onboarding:

    • Create a cheat sheet for the package’s API and common patterns (e.g., email, slug validation).
    • Add examples to your project’s style guide or developer documentation.

Gotchas and Tips

Pitfalls

  1. PCRE Limitations:

    • The package doesn’t expose advanced PCRE features like recursive patterns or complex lookbehinds. For these, fall back to raw preg_* or consider a more specialized library.
    • Workaround: Document unsupported features in your team’s style guide.
  2. Type Safety Assumptions:

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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor