Search code examples
phppattern-matching

A pattern-matching function in PHP


I'm looking for a function, class or collection of functions that will assist in the process of pattern matching strings as I have a project that requires a fair amount of pattern matching and I'd like something easier to read and maintain than raw preg_replace (or regex period).

I've provided a pseudo example in hopes that it will show what I'm asking.

$subject = '$2,500 + $550 on-time bonus, paid 50% upfront ($1,250), 50% on delivery ($1,250 + on-time bonus).';
$pattern = '$n,nnn';
pattern_match($subject, $pattern, 0);

would return "$2,500".

$subject = '$2,500 + $550 on-time bonus, paid 50% upfront ($1,250), 50% on delivery ($1,250 + on-time bonus).';
$pattern = '$n,nnn';
pattern_match($subject, $pattern, 1);

would return an array with the values: [$2,500], [$1,250], [$1,250]

The function — as I'm trying to write — uses 'n' for numbers, 'c' for lower-case alpha and 'C' for upper-case alpha where any non-alphanumeric character represents itself.


Solution

  • <?php
    
    // $match_all = false: returns string with first match
    // $match_all = true:  returns array of strings with all matches
    
    function pattern_match($subject, $pattern, $match_all = false)
    {
      $pattern = preg_quote($pattern, '|');
    
      $ar_pattern_replaces = array(
          'n' => '[0-9]',
          'c' => '[a-z]',
          'C' => '[A-Z]',
        );
    
      $pattern = strtr($pattern, $ar_pattern_replaces);
    
      $pattern = "|".$pattern."|";
    
      if ($match_all)
      {
        preg_match_all($pattern, $subject, $matches);
      }
      else
      {
        preg_match($pattern, $subject, $matches);
      }
    
      return $matches[0];
    }
    
    $subject = '$2,500 + $550 on-time bonus, paid 50% upfront ($1,250), 50% on delivery ($1,250 + on-time bonus).';
    $pattern = '$n,nnn';
    
    $result = pattern_match($subject, $pattern, 0);
    var_dump($result);
    
    $result = pattern_match($subject, $pattern, 1);
    var_dump($result);