str_replace只替换php中数组中的第一个变量
我试图替换{}之间的一个变量,但它只是替换第一个变量 我的代码:str_replace只替换php中数组中的第一个变量,php,Php,我试图替换{}之间的一个变量,但它只是替换第一个变量 我的代码: $array_content[]=array("USER_NAME", "John"); $array_content[]=array("LOGIN_LINK", 'http://exampl.com/signin'); $array_content[]=array("SITE_NAME", 'Google'); $content = "
$array_content[]=array("USER_NAME", "John");
$array_content[]=array("LOGIN_LINK", 'http://exampl.com/signin');
$array_content[]=array("SITE_NAME", 'Google');
$content = "Welcome to {{SITE_NAME}}, Hi, {{USER_NAME}}, now you can login here: {{LOGIN_LINK}}";
foreach ($array_content as $key=>$value){
$mailcontent = str_replace("{{$value[0]}}", $value[1],$content);
}
$mailcontent = stripslashes($mailcontent);
echo $mailcontent;
结果:
欢迎来到{Google},嗨,{USER\u NAME},我们想感谢您的注册,现在您可以在这里登录:{login\u LINK}您正在将
str\u replace()
的结果移动到循环中的一个新变量中,因此丢失更改
$array_content[]=array("USER_NAME", "John");
$array_content[]=array("LOGIN_LINK", 'http://exampl.com/signin');
$array_content[]=array("SITE_NAME", 'Google');
$content = "Welcome to {{SITE_NAME}}, Hi, {{USER_NAME}}, now you can login here: {{LOGIN_LINK}}";
foreach ($array_content as $key=>$value){
$content = str_replace("{{" . $value[0] . "}}", $value[1],$content);
//^^^ changed here and ^^ ^^
}
$mailcontent = stripslashes($content);
您也可以这样做,因为str_replace()接受参数1和2的数组
$array_content = array("{{USER_NAME}}"=> "John",
"{{LOGIN_LINK}}"=> 'http://exampl.com/signin',
"{{SITE_NAME}}"=> 'Google');
$find = array_keys($array_content);
$replace = array_values($array_content);
$content = "Welcome to {{SITE_NAME}}, Hi, {{USER_NAME}}, now you can login here: {{LOGIN_LINK}}";
$mailcontent = str_replace($find, $replace,$content);
echo $mailcontent;
这里有两个问题:
$content
变量,而不保存结果。如果将$mailcontent
定义为$content
,则可以使用str_replace()
,将$mailcontent
作为主题,将$mailcontent
作为接收新值的变量{}
大括号用于在字符串插值中封装变量名,因此,我更新了代码以使用简单的concated字符串。(来源:,请参阅“使用{$获得文字{$。一些示例来说明…”一节)在双引号字符串中,
{}
可用于解析变量。请参阅:
您可能想做:
str_replace('{{' . $value[0] . '}}', $value[1], $content);
此外,在循环中,您正在覆盖每个循环的$mailcontent
值。因此,只有最后一个变量将被替换。您希望类似于:
$mailcontent = $content;
foreach ($array_content as $key=>$value){
$mailcontent = str_replace('{{' . $value[0] . '}}', $value[1], $mailcontent);
}
我没有意识到这一点,但现在它只是将一个大括号{{SITE_NAME}替换为{Google}更改了str_replace()的第一个参数
$mailcontent = $content;
foreach ($array_content as $key=>$value){
$mailcontent = str_replace('{{' . $value[0] . '}}', $value[1], $mailcontent);
}