Why does the following code:
<?php echo preg_replace("/(.*)/", "$1.def", "abc");
Output abc.def.def instead of abc.def?
I’m interested in understanding why the repetition occurs.
Using /(.+)/ or /^(.*)$/ works as expected, but I’m not looking for a solution, just asking a question (although these patterns may be related to the answer).
Tinker with a live version here.
Because
.*matches the empty substring at the end of the string. It means there are two matches to the stringabc:abc→abc.def.defwhich gives
abc.def.def.Edit: Detail of why it happens is explained in String.replaceAll() anomaly with greedy quantifiers in regex.