-1

我正在尝试将动态内容添加到 HTML 以创建动态电子邮件模板。

所以在我的 HTML 中我有

    $html = '<b>Its a html {name} content email {email} here</b>';

我想在我的 HTML 中替换 {name} 和 {email} 的值,这样

$arraydata = ["name"=>"Allan","email"=>"al@al.com"];

那么我该如何继续,以便附加到 HTML 正文的最终 HTML 是

'<b>Its a html Allan content email al@al.com here'

我努力了

$newHtml = "";
foreach ($keyvals as  $key=>$val){
        //itereate through html file and replace keys with values
        //am stuck on how to replace all keys and create the above.
        //the keys above can be many 
    }
return $newHtml;
4

3 回答 3

1

我会这样进行:

$html = '<b>Its a html {name} content email {email} here</b>';
$arraydata = ["name"=>"Allan","email"=>"al@al.com"];

foreach ($arraydata as $key => $value) {
    $html = str_replace('{' . $key . '}', $value, $html);
}

return $html;

返回值为:

"<b>Its a html Allan content email al@al.com here</b>"
于 2019-08-18T16:55:49.700 回答
1

您可以使用下面的代码,如果占位符有多个外观,它将替换如下:

var replaceAll = function(string, replacingItem, replaceWith) {
   return string.toString().replace(new RegExp(replacingItem, 'g'), replaceWith);
};

$html = '<b>Its a html {name} content email {email} here</b>';
$arraydata = ["name"=>"Allan","email"=>"al@al.com"];

foreach ($arraydata as $key => $value) {
    $html = replaceAll($html, '{' . $key . '}', $value);
}

return $html;

希望对你有帮助

于 2019-08-18T17:45:49.670 回答
0

在这种情况下,我会做

    $arraydata = ["name"=>"Allan","email"=>"al@al.com"];
    echo $html = '<b>Its a html '. $arraydata['name'].' content email '. $arraydata['email'].' here</b>';

输出:这是一个 html Allan 内容电子邮件 al@al.com 这里

于 2019-08-18T17:13:23.940 回答