/** * * Gives a unique id to each named capture within a regex. * * Reassigns unique identifiers to named captures within a regular expression. The new * identifiers will have the form "prefix_x", where "prefix" is given by the $prefix * parameter, and "x" a unique identifier starting from 0. * * @param string $pattern * Regex pattern containing potential named captures to be renamed. * * @param array $correspondances * On output, will hold an associative array whose keys are the new capture group names, and values the old ones. * * @param string $prefix * Prefix string for capture name replacements. * * @return string * Returns the input pattern with all named captures replaced by unique identifiers. * * @notes * This method, along with the GroupNamedCaptures() one, is used by the Preg*Ex methods * to allow processing of regular expressions having duplicate named captures. * */ public static function RenumberNamedCaptures($pattern, &$correspondances = [], $prefix = 'match_') { static $re = '/ \\( \\? P < (?P<pattern> [^>]+ ) > /imsx'; // Get named captures if (self::PregMatchAll($re, $pattern, $matches, PREG_OFFSET_CAPTURE)) { $index = 0; $pattern_matches = []; // Loop through pattern matches foreach ($matches['pattern'] as $match) { $pname = $match[0]; $poffset = $match[1]; $newpattern = "{$prefix}{$index}"; // Build the correspondance array $correspondances[$newpattern] = $pname; // Add this entry (old name, new name, offset) into an array for the Regex::MultiSubsrReplace() method $pattern_matches[] = [$pname, $newpattern, $poffset]; $index++; } // Perform the multiple-string replace $new_pattern = Regex::MultiSubstrReplace($pattern, $pattern_matches); } else { $new_pattern = $pattern; } // All done, return return $new_pattern; }