我有一个送出的网站电子邮件(使用PHPMailer的),我想要做什么,基本上是PHP的替换与我喂它内容email.tpl文件中的所有placheholders的功能。 对我来说,问题是我不希望因此重复的代码,为什么我创建了一个功能(如下图)。
如果没有一个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个占位符和有值在电子邮件模板的功能。
我不知道我是否会需要用到的脚本(s)表示将使用功能和一个数组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!";
}
}