Double or Single Quotes on preg_replace ?

Today I run into a curious issue while implementing payment processing via authorize.net on a website. The issue has nothing to do with the website or authorize.net, but rather with php.

On the website, users ca chose a donation option. This options have values like “Donation Option – $50”. I have to submit them like that because that value needs to be passed to authorize.net as a custom field, but in order to capture the monetary value, I need to parse that string. At some point I end up wit just the number, and the sign (ej: $50). At this point it is just a matter of removing the sign from the number, so I do this:

preg_replace("/\$/", "", $money);//$money holds the value, in this case "$50"

But that does not work. Inspecting a bit further I realize what the problem is:

preg_replace("/\$/", "B", $money);// gives back "$50B"

this means, that piece of code is actually being interpreted as:

preg_replace("/$/", "B", $money);

so the $ is not being escaped, and we are loosing / at some point. So I decided to do a little duckduckgoing (that is like googling, but for duckduckgo.com), and I find this form discussion:

http://board.phpbuilder.com/board/showthread.php?t=10124101

Let’s try it out:

preg_replace("/\\$/", "", $money);//gives back 50.

This works!, but why? Well, the fact that this works means we need to escape the \ as well in order to be able to scape the $. What about something a bit different:

preg_replace('/\$/', "", $money);//gives back 50

This works too! At this point I remember that in php strings are treated differently depending on how you quote them. You can read more about it on http://www.php.net/manual/en/language.types.string.php

So, I conclude that this problem has to do with string expansion, and that is is better to use single quotes (‘) instead of double quotes (“) when working with regexps in php.