Instead you have to use strings which get interpolated once when being stored as a string

That's a very good reason not to use the "quote" syntax in PHP, so that strings don't get interpreted (or interpolated).

$ans = preg_replace('\$', '\\$', $ans)