spatie/regex

repository·main·Indexed 22 days ago

https://github.com/spatie/regex

An object-oriented interface for PHP's built-in preg_* functions. It replaces error-prone patterns with a cleaner API, providing MatchResult, MatchAllResult, and ReplaceResult objects to handle regex matching and replacements. It simplifies error handling by throwing RegexFailed exceptions instead of requiring manual checks of preg_last_error().

Tokens
2.5K
Snippets
12
Records
13
Agent score
77%

What's inside spatie/regex

  1. Install spatie/regex via Composer

    main

    You can install the package using composer to get a cleaner interface for PHP's built-in preg_* functions.

    composer require spatie/regex
  2. Handle regex errors with RegexFailed

    main

    Instead of checking preg_last_error(), spatie/regex throws a RegexFailed exception whenever a regex operation fails. This allows you to use standard PHP try/catch blocks for error handling.

    try {
        Regex::match('/(unclosed-group/', 'abc');
    } catch (\Spatie\Regex\RegexFailed $exception) {
        // Handle error
    }
  3. Replace patterns with Regex::replace()

    main

    Use Regex::replace() to replace occurrences of a pattern in a subject. It returns a ReplaceResult object.

    Usage Patterns

    • Simple replacement: Pass a string as the replacement.
    • Callback replacement: Pass a callable that receives a MatchResult instance. This allows for dynamic replacements based on the content of the match.
    • Arrays: Patterns, replacements, and subjects can be arrays, behaving identically to preg_replace.

    ReplaceResult Methods

    • result(): mixed: Returns the resulting string (or array of strings) after replacement.
    use Spatie\Regex\Regex;
    use Spatie\Regex\MatchResult;
    
    // Simple string replacement
    $result = Regex::replace('/a/', 'b', 'abc')->result(); // 'bbc'
    
    // Callback replacement
    $result = Regex::replace('/a/', function (MatchResult $matchResult) {
        return $matchResult->result() . 'Hello!';
    }, 'abc')->result(); // 'aHello!bc'
  4. Match all occurrences with Regex::matchAll()

    main

    Use Regex::matchAll() to find all occurrences of a pattern in a subject. It returns a MatchAllResult object.

    MatchAllResult Methods

    • hasMatch(): bool: Returns true if at least one match was found.
    • results(): array: Returns an array of MatchResult objects, allowing you to iterate through every match and access groups via group() or the full match via result().
    use Spatie\Regex\Regex;
    
    $allMatches = Regex::matchAll('/ab([a-z])/', 'abcabd');
    
    if ($allMatches->hasMatch()) {
        foreach ($allMatches->results() as $match) {
            echo $match->result(); // 'abc', then 'abd'
            echo $match->group(1); // 'c', then 'd'
        }
    }
  5. Match a pattern once with Regex::match()

    main

    Use Regex::match() to find the first occurrence of a pattern in a subject. It returns a MatchResult object.

    MatchResult Methods

    • hasMatch(): bool: Returns true if the pattern matched the subject.
    • result(): string|null: Returns the full match string, or null if no match was made.
    • group(int $id): string: Returns the contents of a captured group (1-based index). Throws a RegexFailed exception if the group does not exist.
    • resultOr(string $default): string: Returns the full match or a provided default if no match was found.
    • groupOr(int $id, string $default): string: Returns the captured group or a provided default if the group/match is missing.
    use Spatie\
    egex\\Regex;
    
    // Basic match
    $match = Regex::match('/a/', 'abc');
    $match->hasMatch(); // true
    $match->result();   // 'a'
    
    // Capturing groups
    $match = Regex::match('/a(b)/', 'abc');
    $match->group(1);    // 'b'
    
    // Using defaults
    $match = Regex::match('/a(b)/', 'xyz');
    $match->resultOr('default'); // 'default'
    $match->groupOr(1, 'default'); // 'default'
  6. Handle regex operation failures with RegexFailed

    main
    When using the spatie/regex package, certain operations may fail (e.g., a pattern doesn't match or a capture group is missing). These failures throw a Spatie\Regex\Exceptions\RegexFailed exception. You can catch this exception to handle errors gracefully during matching or replacement operations.
  7. Retrieve individual match results from MatchAllResult

    main

    When using a matchAll operation, the MatchAllResult object contains the aggregate result. You can call the results() method to transform the raw matches into an array of individual MatchResult objects. This allows you to iterate over each specific match found in the subject string and access its specific capture groups.

    /** @var MatchAllResult $matchAllResult */
    $individualResults = $matchAllResult->results();
    
    foreach ($individualResults as $result) {
        // Each $result is an instance of Spatie\Regex\MatchResult
        if ($result->hasMatch()) {
            // Access specific match data
        }
    }
  8. Access regex groups in MatchResult

    main

    You can extract specific capture groups from a MatchResult using their integer index or their named identifier:

    • group(int|string $group): Returns the content of the specified group. Throws RegexFailed::groupDoesntExist() if the group is not present in the matches.
    • namedGroup(int|string $group): An alias for group(); allows accessing groups by name or index.
    • groupOr(int|string $group, string $default): Returns the content of the specified group, or the $default value if the group does not exist.
    • groups(): Returns the entire array of matches (including the full match and all capture groups).
    $matchResult = MatchResult::for('/(?<name>\w+) is (\d+)/', 'Alice is 30');
    
    $name = $matchResult->group('name'); // 'Alice'
    $age = $matchResult->group(2);        // '30'
    $safeAge = $matchResult->groupOr(3, 'unknown'); // 'unknown'
    $allGroups = $matchResult->groups();
  9. Create a MatchResult using for()

    main

    To perform a single regex match and obtain a MatchResult object, use the static for() method. This method executes the pattern against the subject using preg_match with the PREG_UNMATCHED_AS_NULL flag. If the regex pattern is invalid or fails, it throws a Spatie\Regex\Exceptions\RegexFailed exception.

    use Spatie\Regex\MatchResult;
    
    $matchResult = MatchResult::for('/pattern/', 'subject string');
  10. Retrieve match results from MatchResult

    main

    Once you have a MatchResult instance, you can inspect the match status and extract the matched content using the following methods:

    • hasMatch(): Returns true if the pattern matched the subject, false otherwise.
    • result(): Returns the full match (the first element of the matches array) as a string, or null if no match was found.
    • resultOr(string $default): Returns the full match as a string, or the provided $default value if no match was found.
    $matchResult = MatchResult::for('/(\d+)/', 'ID: 123');
    
    if ($matchResult->hasMatch()) {
        $fullMatch = $matchResult->result(); // '123'
        $fallback = $matchResult->resultOr('none');
    }
  11. Get the transformed string and replacement count from ReplaceResult

    main

    Once you have a ReplaceResult instance, you can access the outcome of the operation using the following methods:

    • result(): Returns the transformed string or array (depending on the input subject).
    • count(): Returns the int number of replacements that were actually performed.
    $result = ReplaceResult::for('/pattern/', 'replacement', 'subject', -1);
    
    $transformed = $result->result();
    $numReplacements = $result->count();
  12. Handle regex replacement results with ReplaceResult::for()

    main

    Use ReplaceResult::for() to perform a regex replacement and receive a result object containing both the transformed string (or array) and the number of replacements made.

    This method supports both static string replacements and dynamic replacements using a callable. If the replacement is a callable, the callback receives a MatchResult object instead of a raw matches array, allowing for more expressive replacement logic.

    If the replacement fails, it throws a Spatie\Regex\Exceptions\RegexFailed exception.

    use Spatie\Regex\ReplaceResult;
    
    $result = ReplaceResult::for(
        '/foo/i',           // pattern
        'bar',               // replacement
        'foo bar foo',       // subject
        -1                   // limit (-1 for all)
    );
    
    echo $result->result(); // "bar bar bar"
    echo $result->count(); // 2