I am using this preg_replace
echo preg_replace('/.*/','r','string');
https://eval.in/720293
I was expecting it should output r
But the output is
rr
Can someone explain why it echo two r ?
Because preg_replace uses global flag and .* matches first the whole string and then the empty string at the end and therefore you see two times the r.
If you want to replace just the string you have to be more explicit with the pattern. For an example, you can use the following ^.*.
Other option is to add limit to preg_replace to replace only the first match:
preg_replace('/.*/','r','string', 1)
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