David
David

Reputation: 2423

PHP preg_replace text variable

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

Upvotes: 2

Views: 2155

Answers (4)

Shivek Parmar
Shivek Parmar

Reputation: 2993

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

Upvotes: 0

Bart Kiers
Bart Kiers

Reputation: 170158

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?

Upvotes: 0

Ben Karel
Ben Karel

Reputation: 4711

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

Upvotes: 1

Gumbo
Gumbo

Reputation: 655269

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";

Upvotes: 7

Related Questions