Pavel Koryagin
Pavel Koryagin

Reputation: 1481

preg_replace produces unexpected duplicate with a very simple RegEx

var_dump(
  preg_replace('/.?$/s', "x", 'abc'),
  preg_replace('/.$/s',  "x", 'abc')
);

Outputs:

string(4) "abxx" <-- strange, isn't it?
string(3) "abx"

How's that possible?

Upvotes: 2

Views: 48

Answers (1)

Barmar
Barmar

Reputation: 781058

preg_replace replaces all matches in the string. So after doing each replacement, it searches for another match starting after the place where it made the previous replacement.

So it first looks for /.?$/ and finds c, and replaces it with x, resulting in abx. Then, it looks again for /.?$/ starting right after the x. Since .? means to match 0 or 1 characters, it matches the zero-length string at the end of the string, and replaces it with x. Then it stops because it has reached the end of the string.

Upvotes: 1

Related Questions