views:

309

answers:

3

I want to echo a string with the variable inside including the ($) like so:

echo "$string";

I dont want it to echo the variable for string, I want it to echo '$string' itself, and not the contents of a variable. I know I can do this by adding a '\' in front of the ($), but I want to use preg_replace to do it. I tried this and it doesnt work:

$new = preg_replace("/\$/","\\$",$text);
+4  A: 

Use single quotes for your string declaration:

echo '$string';

Variables inside single quotes do not get expanded:

Note: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

Another solution would be to escape the $ like you already did within the preg_replace call:

echo "\$string";
Gumbo
haha wow thanks
David
+1  A: 

If I understand your question correctly, you can't use preg_replace to do what you want. preg_replacegets its arguments after variable substitution takes place.

So either there's nothing for preg_replaceto replace (because the substitution already occurred), or there is no need for preg_replaceto do anything (because the dollar sign was already escaped).

Ben Karel
A: 

As you observed, the $ is treated for variable interpolation inside double quoted strings. So your regex pattern should be constructed using single quoted strings as well. Also, the $ is a special character inside the regex-replacement string, so you need to escape it extra:

preg_replace('/\$/', '\\\\$', $text)

But there is no need for the preg_ function here. str_replace should do it:

str_replace('$', '\\$', $text)

This might clear things up for you, but as Gumbo suggests: why not use single quotes to echo?

Bart Kiers