2

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 Answers 4

7

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";
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

0

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?

Comments

0

Well I think you want to remove the text which exists in some variables. Then you can do it like

 $foo = '123';  
 $bar = 'bqwe';                      
 $str= preg_replace("/".$foo ."/", '', $str, 1);
 $str= preg_replace("/".$bar ."/", '', $str, 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.