用PHP替换多个占位符? [英] Replace multiple placeholders with PHP?

查看:167
本文介绍了用PHP替换多个占位符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个发送站点电子邮件的函数(使用phpmailer),我想要做的事情基本上是用php来替换email.tpl文件中的所有placheholders,并提供它所提供的内容。对我来说问题是我不想重复代码,因此我创建了一个函数(下面)。

没有php函数,我会在脚本

  //电子邮件模板文件
$ email_template =email.tpl;

//从文件
$ message = file_get_contents($ 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值并循环遍历占位符并替换他们与那里值。



这是我在上面提到的功能。我评论了这个脚本,这可能会更容易解释。

  //将需要使用PERHAPS作为我的占位者的阵列,并且有值x脚本
//进入功能?
函数phpmailer($ to_email,$ email_subject,$ email_body,$ email_tpl){

//包括php邮件程序类
require_once(class.phpmailer.php);

//发送至电子邮件(receipent)
全局$ to_email;
//为邮件添加正文
global $ email_subject;
//电子邮件正文
全球$ email_body;
//电子邮件模板
全球$ email_tpl;

//获取电子邮件模板
$ message = file_get_contents($ email_tpl);

//用x脚本替换电子邮件模板占位符
//找到[它具有相关的价值。
//不确定是否需要在此处循环通过所有
//占位符循环我提供了该函数并将其替换为相应的值
$ email_body = str_replace([{ \}]],'replace',$ email_body);

//创建PHPMailer的对象
$ mail = new PHPMailer();

//通知班级使用smtp
$ mail-> IsSMTP();
//启用smtp认证
$ mail-> SMTPAuth = SMTP_AUTH;
// smtp服务器的主机
$ mail-> Host = SMTP_HOST;
// smtp服务器的端口
$ mail->端口= SMTP_PORT;
// smtp用户名
$ mail->用户名= SMTP_USER;
// smtp用户密码
$ mail->密码= SMTP_PASS;
//邮件字符集
$ mail-> CharSet = MAIL_CHARSET;

//从电子邮件地址设置
$ mail-> SetFrom(FROM_EMAIL);
//寻址
$ mail-> AddAddress($ to_email);
// email subject
$ mail-> Subject = $ email_subject;
// html message body
$ mail-> MsgHTML($ email_body);
//纯文本消息正文(无html)
$ mail-> AltBody(strip_tags($ email_body));

//最后发送邮件
if(!$ mail-> Send()){
echoMailer Error:。 $ MAIL-> ERRORINFO;
} else {
echo发送成功!;



$ div $解析方案

简单,请参阅 strtr ­文档

  $ vars = array(
[{USERNAME}]= > $ username,
[{EMAIL}]=> $ email,
);

$ message = strtr($ message,$ vars);

根据需要添加尽可能多的(或更少)替换对。但是我建议你在调用 phpmailer 函数之前处理模板,这样可以保持分开:模板化和邮件发送:

  class MessageTemplateFile 
{
/ **
* @var字符串
* /
private $ file;
/ **
* @var string [] varname =>字符串值
* /
私人$ vars;

public function __construct($ file,array $ vars = array())
{
$ this-> file =(string)$ file;
$ this-> setVars($ vars);


public function setVars(array $ vars)
{
$ this-> vars = $ vars;
}

public function getTemplateText()
{
return file_get_contents($ this-> file);

$ b public function __toString()
{
return strtr($ this-> getTemplateText(),$ this-> getReplacementPairs());


private function getReplacementPairs()
{
$ pairs = array();
foreach($ this-> vars as $ name => $ value)
{
$ key = sprintf('[{%s}]',strtoupper($ name)) ;
$ pairs [$ key] =(string)$ value;
}
返回$对;






$ b

用法可以大大简化,然后你可以通过整个模板到任何需要字符串输入的函数。

  $ vars = compact('username','message'); 
$ message = new MessageTemplateFile('email.tpl',$ vars);


I have a function that sends out site emails (using phpmailer), what I want to do is basically for php to replace all the placheholders in the email.tpl file with content that I feed it. The problem for me is I don't want to be repeating code hence why I created a function (below).

Without a php function I would do the following in a script

// 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);

Now I know how to do the rest but I am stuck on the str_replace(), as shown above I have multiple str_replace() functions to replace the placeholders in the email template. What I would like is to add the str_replace() to my function (below) and get it to find all instances of [\] in the email template I give it and replace it with the placeholders values that I will give it like this: str_replace("[\]", 'replace_with', $email_body)

The problem is I don't know how I would pass multiple placeholders and their replacement values into my function and get the str_replace("[{\}]", 'replace_with', $email_body) to process all the placeholders I give it and replace with there corresponding values.

Because I want to use the function in multiple places and to avoid duplicating code, on some scripts I may pass the function 5 placeholders and there values and another script may need to pass 10 placeholders and there values to the function to use in email template.

I'm not sure if I will need to use an an array on the script(s) that will use the function and a for loop in the function perhaps to get my php function to take in xx placeholders and xx values from a script and to loop through the placeholders and replace them with there values.

Here's my function that I referred to above. I commented the script which may explain much easier.

// 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!";
  }
}

解决方案

Simple, see strtr­Docs:

$vars = array(
    "[{USERNAME}]" => $username,
    "[{EMAIL}]" => $email,
);

$message = strtr($message, $vars);

Add as many (or as less) replacement-pairs as you like. But I suggest, you process the template before you call the phpmailer function, so things are kept apart: templating and mail sending:

class MessageTemplateFile
{
    /**
     * @var string
     */
    private $file;
    /**
     * @var string[] varname => string value
     */
    private $vars;

    public function __construct($file, array $vars = array())
    {
        $this->file = (string)$file;
        $this->setVars($vars);
    }

    public function setVars(array $vars)
    {
        $this->vars = $vars;
    }

    public function getTemplateText()
    {
        return file_get_contents($this->file);
    }

    public function __toString()
    {
        return strtr($this->getTemplateText(), $this->getReplacementPairs());
    }

    private function getReplacementPairs()
    {
        $pairs = array();
        foreach ($this->vars as $name => $value)
        {
            $key = sprintf('[{%s}]', strtoupper($name));
            $pairs[$key] = (string)$value;
        }
        return $pairs;
    }
}

Usage can be greatly simplified then, and you can pass the whole template to any function that needs string input.

$vars = compact('username', 'message');
$message = new MessageTemplateFile('email.tpl', $vars);

这篇关于用PHP替换多个占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆