-1
preg_replace('/[^.]*$/','png','asdf.jpgea.jpg')

The output is asdf.jpgea.pngpng, why there are two png in the end?

Meanwhile,

preg_replace('/\w$/','png','asdf.jpgea.jpg')

outputs asdf.jpgea.jppng.

Is the * affecting how $ behaves?

shenkwen
  • 2,994
  • 5
  • 31
  • 65
  • 1
    This has been asked many times. `*` makes it match an empty string. `$` is a zero width assertion, thus the first match is an empty string before the end of string, and the second match is the end of string itself. It is not affecting all regex flavors, but the majority of them. – Wiktor Stribiżew Oct 11 '17 at 09:33

1 Answers1

0

The * (0 or more times) isn't affecting how the $ sign behaves, but you need to change it to a + (1 or more times) to get the result you expect:

preg_replace('/[^.]+$/','png','asdf.jpgea.jpg');

Essentially, the * is resulting in jpg getting matched twice instead of once, because * also matches nothing.

The technical explanation behind this is pretty complex, and I don't feel like typing it all out, so here's a good link where someone else explains it:

https://stackoverflow.com/a/3420778/8001997

patrick3853
  • 894
  • 6
  • 12