如何使用PHP str_replace替换以$开头的值


How to use PHP str_replace to replace values started with $

我正在我的网站中制作提要功能,用户可以在其中播放操作。

我将不同的操作消息存储为

 {item:$user} added {var:$count} photo(s) to the album {item:$album_name}

在数据库中,因为我在运行时得到了不同的操作消息。

所以当我使用str_replace作为

$body =  "{item:$user} added {var:$count} photo(s) to the album {item:$album_name}";
$body =  str_replace("{item:$user}",$userName,$body);

它不会替换文本并按原样显示,但当我删除"$user}"时,它会替换字符串"{item:"。

我的剧本有什么问题吗?或者我必须使用一些特殊的方法。

谢谢。

当PHP解析您的str_replace语句时,由于您的"{item:$user}"是用双引号括起来的,因此PHP将在返回字符串之前尝试评估字符串中的变量和函数。因此,它正在寻找$user,认为它是一个变量。试着用单引号替换双引号,看看效果如何。

我还建议让你的模板占位符更简单,因为你只是用硬编码的针代替字符串。在您的示例中,{user}也可以代替{var:$user}。或者更改替换方法以利用多个部件占位符

不要这样做:

var $s = "$variable inside a string"

只需这样做(单引号):

var $s = '$variable inside a string'

这样它就不会用它的值替换字符串中的变量。使用双引号时,字符串中的变量将替换为其值。

使用单引号:

$body =  str_replace('{item:$user}',$userName,$body);

我也会给你和其他人一样的答案:

$var = 'EXAMPLE';
// double quotes take a string with variables, but interprents them 'gently'
echo " this is $var "; // will result in [ this is EXAMPLE ]
// Single quotes all a litteral string. This means it will not _parse_ the values (or functions)
echo ' this is $var '; // will result in [ this is $var ]
// If you want the dolarsign AND doublequotes, you have to escape
echo " this is '$var "; // will result in [ this is $var]