Is there a way to specify how many times a reference to captured group must be repeated in the replacement string? [duplicate]

5 days ago 1
ARTICLE AD BOX

Using str_repeat works to prepare the replacement string to be like "$1$1" for preg_replace.

But there might be a catch here if this is not for a single character because:

Repeating a capture group will only capture the value of the last iteration.

So in this case it works for a single character Z, but if you want to match multiple repetitions of ABC like this with a capture group (ABC){3,}

The output might be unexpected:

$billing = "ABCABCABC"; $repetitions = 2; $result = preg_replace('/(ABC){3,}/', str_repeat("$1", $repetitions), $billing); echo $result; // ABCABC

Note that you don't need a capture group, you can use $0 for the full match and repeat that:

$billing = "ABCABCABC"; $repetitions = 2; $result = preg_replace('/(?:ABC){3,}/', str_repeat("$0", $repetitions), $billing); echo $result; // ABCABCABCABCABCABC

Or with a callback:

$result = preg_replace_callback( '/(?:ABC){3,}/', fn($m) => str_repeat($m[0], $repetitions), $billing );
Read Entire Article