Skip to content

Commit f5e7b70

Browse files
committed
Use Arrays for Regex and Format Strings
1 parent 34ff753 commit f5e7b70

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

src/StringHelper.php

+23-17
Original file line numberDiff line numberDiff line change
@@ -56,25 +56,31 @@ public static function increment($string, $style = 'default', $n = 0)
5656
{
5757
$styleSpec = static::$incrementStyles[$style] ?? static::$incrementStyles['default'];
5858

59-
// Regular expression search and replace patterns for both cases
60-
if ($style === 'default') {
61-
if (preg_match('#\((\d+)\)$#', $string, $matches)) {
62-
$n = empty($n) ? ($matches[1] + 1) : $n;
63-
$string = preg_replace('#\((\d+)\)$#', "($n)", $string);
64-
} else {
65-
$string .= ' (2)';
66-
}
59+
// Regular expression search and replace patterns for both styles
60+
if (\is_array($styleSpec[0])) {
61+
$rxSearch = $styleSpec[0][0];
62+
$rxReplace = $styleSpec[0][1];
6763
} else {
68-
$rxSearch = '#-(\d+)$#'; // Match the trailing number after a hyphen (e.g., "dog-2")
69-
$rxReplace = '-%d'; // Replace it with "-number"
64+
$rxSearch = $rxReplace = $styleSpec[0];
65+
}
7066

71-
if (preg_match($rxSearch, $string, $matches)) {
72-
$n = empty($n) ? ($matches[1] + 1) : $n;
73-
$string = preg_replace($rxReplace, sprintf($rxReplace, $n), $string);
74-
} else {
75-
$n = empty($n) ? 2 : $n;
76-
$string .= sprintf($rxReplace, $n);
77-
}
67+
// New and old (existing) sprintf formats
68+
if (\is_array($styleSpec[1])) {
69+
$newFormat = $styleSpec[1][0];
70+
$oldFormat = $styleSpec[1][1];
71+
} else {
72+
$newFormat = $oldFormat = $styleSpec[1];
73+
}
74+
75+
// Check if we are incrementing an existing pattern or appending a new one
76+
if (preg_match($rxSearch, $string, $matches)) {
77+
// If a match is found, increment the existing number
78+
$n = empty($n) ? ($matches[1] + 1) : $n;
79+
$string = preg_replace($rxReplace, sprintf($oldFormat, $n), $string);
80+
} else {
81+
// If no match is found, append the number (default is 2)
82+
$n = empty($n) ? 2 : $n;
83+
$string .= sprintf($newFormat, $n);
7884
}
7985

8086
return $string;

0 commit comments

Comments
 (0)