user3472449
user3472449

Reputation: 59

php str_replace dollar sign

Hi I am having trouble replacing a string with dollar sign

$string = "The $NAME brown fox jumped over the lazy dog.";
echo preg_replace('/\$NAME/', "Sample Name", $string);

Output:

The brown fox jumped over the lazy dog.

The problem is that $NAME is not replaced with Sample Name. I will be happy if there will be any help to solve my problem.

Upvotes: 2

Views: 2387

Answers (2)

Samosa
Samosa

Reputation: 845

Try

$string = 'The $NAME brown fox jumped over the lazy dog.';
echo str_replace('$NAME', "Sample Name", $string);

The solution to put the string in single quotes rather than in double-quotes (") since PHP will try to interpret for special characters.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798744

That's because PHP has helpfully replaced the text in the string with the contents of $NAME for you. Tell it to not do that.

$string = 'The $NAME brown fox jumped over the lazy dog.';

Upvotes: 4

Related Questions