2014-07-21 47 views
2

你好我无法用美元符号替换字符串PHP str_replace函数美元符号

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

输出:

The brown fox jumped over the lazy dog. 

的问题是,$ NAME不与样品名称取代。 如果有任何帮助解决我的问题,我会很高兴。

+0

既然你不是活得在做任何正则表达式搜索和替换时,我建议使用str_replace代替 – Samosa

回答

4

这是因为PHP有​​helpfully replaced the text in the string with the contents of $NAME你。告诉它不要那样做。

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

特别是...使用双引号允许字符串插值,其中变量名称被解析并被替换为字符串值单引号不允许字符串插值,乐在那里提供'$ NAME'的字面值。 – Brad

+0

啊,好的..谢谢。 – user3472449

+0

我会将'$ NAME'改为'{NAME}'。意思是你不能无意中给它分配一个变量 – dpDesignz

0

尝试

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

解决方案放入单引号括起来,而不是双引号(“),因为PHP将试图解释为特殊字符。

+2

...这不起作用。它试图使用$作为分隔符并引发警告。 – ahruss

+0

它不起作用 – Cattla

+0

对不起......其类型我的意思是str_replace! – Samosa