Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why preg_replace giving this result

Tags:

php

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 ?

like image 725
beginner Avatar asked Apr 02 '26 03:04

beginner


1 Answers

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)

like image 113
Anton Grigorov Avatar answered Apr 08 '26 04:04

Anton Grigorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!