Search code examples
phpregexdollar-sign

preg_replace and dollar sign


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?


Solution

  • 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