Escaping dollar signs in PHP regular expressions
I had some problems matching dollar signs in PHP regexp’s:
$str = 'Bacon $ham eggs and $spam'; preg_match_all("|$|", $str, $matches); print_r($matches);
Gives
Array ( [0] => Array ( [0] => ) )
It does work when double escaping the $
preg_match_all("|\$|", $str, $matches);
Gives
Array ( [0] => Array ( [0] => $ [1] => $ ) )
This problem occurs because PHP substitutes $variables in strings enclosed in “double quotes”. So, actually the problem can very easily be solved by just replacing double with single quotes:
preg_match_all('|$' $str, $matches);