[英]Php change mulitple sections in a word to a pre-defined value
我正在嘗試將動態內容添加到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;
我將這樣進行:
$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>"
您可以使用以下代碼,如果出現多個占位符,則將替換以下代碼:
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;
希望對您有幫助
在這種情況下,我會
$arraydata = ["name"=>"Allan","email"=>"al@al.com"];
echo $html = '<b>Its a html '. $arraydata['name'].' content email '. $arraydata['email'].' here</b>';
輸出:此處是html Allan內容的html al@al.com電子郵件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.