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 string abc
:
abc
→ abc.def
.def
which gives abc.def.def
.
Edit: Detail of why it happens is explained in String.replaceAll() anomaly with greedy quantifiers in regex.
It's the expected behaviour: https://bugs.php.net/bug.php?id=53855
This is expected behaviour and nothing peculiar to PHP. The * quantifier allows an "empty" match to occur at the end of your subject string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With