@@ -56,25 +56,31 @@ public static function increment($string, $style = 'default', $n = 0)
56
56
{
57
57
$ styleSpec = static ::$ incrementStyles [$ style ] ?? static ::$ incrementStyles ['default ' ];
58
58
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 ];
67
63
} 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
+ }
70
66
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 );
78
84
}
79
85
80
86
return $ string ;
0 commit comments