我有一个发送站点电子邮件的功能(使用 phpmailer),我想要做的基本上是让 php 用我提供的内容替换 email.tpl 文件中的所有占位符。对我来说,问题是我不想重复代码,因此我创建了一个函数(如下)。
如果没有 php 函数,我会在脚本中执行以下操作
// email template file
$email_template = "email.tpl";
// Get contact form template from file
$message = file_get_contents($email_template);
// Replace place holders in email template
$message = str_replace("[{USERNAME}]", $username, $message);
$message = str_replace("[{EMAIL}]", $email, $message);
现在我知道如何做剩下的了,但我卡在了str_replace()
,如上所示,我有多个str_replace()
函数来替换电子邮件模板中的占位符。我想要的是添加str_replace()
到我的函数(如下)并让它[\]
在我给它的电子邮件模板中找到所有实例并将其替换为我将给它的占位符值,如下所示:str_replace("[\]", 'replace_with', $email_body)
问题是我不知道如何将多个占位符及其替换值传递到我的函数中,并让str_replace("[{\}]", 'replace_with', $email_body)
处理我给它的所有占位符并用相应的值替换。
因为我想在多个地方使用该函数并避免重复代码,所以在某些脚本上我可能会传递函数 5 个占位符和值,而另一个脚本可能需要将 10 个占位符和值传递给要在电子邮件模板中使用的函数。
我不确定我是否需要在将使用函数的脚本上使用一个数组,并在函数中使用一个for
循环,也许可以让我的 php 函数从脚本中获取 xx 占位符和 xx 值并遍历占位符并用那里的值替换它们。
这是我上面提到的我的功能。我评论了可能更容易解释的脚本。
// WILL NEED TO PASS PERHAPS AN ARRAY OF MY PLACEHOLDERS AND THERE VALUES FROM x SCRIPT
// INTO THE FUNCTION ?
function phpmailer($to_email, $email_subject, $email_body, $email_tpl) {
// include php mailer class
require_once("class.phpmailer.php");
// send to email (receipent)
global $to_email;
// add the body for mail
global $email_subject;
// email message body
global $email_body;
// email template
global $email_tpl;
// get email template
$message = file_get_contents($email_tpl);
// replace email template placeholders with content from x script
// FIND ALL INSTANCES OF [{}] IN EMAIL TEMPLATE THAT I FEED THE FUNCTION
// WITH AND REPLACE IT WITH THERE CORRESPOING VALUES.
// NOT SURE IF I NEED A FOR LOOP HERE PERHAPS TO LOOP THROUGH ALL
// PLACEHOLDERS I FEED THE FUNCTION WITH AND REPLACE WITH THERE CORRESPONDING VALUES
$email_body = str_replace("[{\}]", 'replace', $email_body);
// create object of PHPMailer
$mail = new PHPMailer();
// inform class to use smtp
$mail->IsSMTP();
// enable smtp authentication
$mail->SMTPAuth = SMTP_AUTH;
// host of the smtp server
$mail->Host = SMTP_HOST;
// port of the smtp server
$mail->Port = SMTP_PORT;
// smtp user name
$mail->Username = SMTP_USER;
// smtp user password
$mail->Password = SMTP_PASS;
// mail charset
$mail->CharSet = MAIL_CHARSET;
// set from email address
$mail->SetFrom(FROM_EMAIL);
// to address
$mail->AddAddress($to_email);
// email subject
$mail->Subject = $email_subject;
// html message body
$mail->MsgHTML($email_body);
// plain text message body (no html)
$mail->AltBody(strip_tags($email_body));
// finally send the mail
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent Successfully!";
}
}