如何阻止 str_replace 更改数组中每个项目的所有实例?

How to stop str_replace from changing all instances in every item in the array?

我正在使用 for 循环循环多维数组,并为循环中的每个项目触发和发送电子邮件。我想将 {{fname}} 更改为密钥中的真实姓名。

foreach($customermarketingarray as $key => $value){
     $customeremail = $value['email'];
     $fname = $value['first_name'];
     $body = str_replace("{{fname}}",$fname,$body);                     
                             }

出于某种原因,除了 {{fname}} 对循环中的每个 fname 使用第一个循环中的名字之外,一切都是独一无二的。如果第一个人是 Joe,则每个 fname Joe

您第一次使用 str_replace 时,它会替换整个正文中出现的 {{fname}}。在进一步的循环迭代中没有什么可以替换的。

使用 preg_replace,它有额外的参数(limit),它规定了最多进行多少次替换。在您的示例中,如果每个名称只有一个 {{fname}},则使用 1 作为计数参数即可。

阅读文档。这是不言自明的。 http://php.net/manual/en/function.preg-replace.php

另一件事是您的数据构造有问题。如果没有额外的规则,您无法区分哪个 {{fname}} 去哪个替换。

不清楚您是否要将 $body 用作模板(我假定为否,因为除了循环迭代中的替换之外,您没有将 $body 用于任何其他用途)。如果 {{fname}} 在正文中多次出现并且您想用循环迭代中的名称一一替换它们,我的回答是有效的。

因为你一直在用一个 $body 一遍又一遍,一旦替换完成,就没有什么可以替换的了。每次迭代都使用 $body 的新版本。

foreach($customermarketingarray as $key => $value){
     $customeremail = $value['email'];
     $fname = $value['first_name'];
     $tempBody = str_replace("{{fname}}",$fname,$body);              
      // now use this $tempBody for display
     }

这样,在循环的每次迭代中,您都会再次从 $body 获得一个新模板,您可以对其进行替换,然后使用它。

使用preg_replace

可以使用 preg_replace 而不是 str_replace 来完成 答案:PHP variables and loops in HTML format

检查并检查是否已弃用,http://php.net/manual/en/function.preg-replace.php

    $body_message = $body;
    foreach($customermarketingarray as $key => $value){
         $customeremail = $value['email'];
         $fname = $value['first_name'];
        // $body = str_replace("{{fname}}",$fname,$body);  
        $body_message  = preg_replace("/{{(.*?)}}/e","@$", $body);                   
    }

使用str_replace

$body_message = $body;
foreach($customermarketingarray as $key => $value){
     $customeremail = $value['email'];
     $fname = $value['first_name'];
     $body_message = str_replace("{{fname}}",$fname,$body);                        
     }

您正在替换每个循环中的变量 $body。只需使用一个新变量来存储结果。请参阅下面的示例。

<?php
$customermarketingarray=array(
    0=>array("email"=>"1@test.com","first_name"=>"Joe1"),
    1=>array("email"=>"2@test.com","first_name"=>"Joe2"),
    2=>array("email"=>"3@test.com","first_name"=>"Joe3"),
    3=>array("email"=>"4@test.com","first_name"=>"Joe4")
);
$body="First Name: {{fname}}<br>Email: {{email}}<br><br>";
foreach($customermarketingarray as $key => $value){
     $customeremail = $value['email'];
     $fname = $value['first_name'];
     $email = $value['email'];
     $res_body .= str_replace(array("{{fname}}","{{email}}"),array($fname,$email),$body);
}
echo $res_body;
?>

以上代码的结果是

First Name: Joe1
Email: 1@test.com

First Name: Joe2
Email: 2@test.com

First Name: Joe3
Email: 3@test.com

First Name: Joe4
Email: 4@test.com