用PHP替换多个占位符?

PHP*_*VER 3 php function placeholder str-replace

我有一个发送网站电子邮件的功能(使用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);
Run Code Online (Sandbox Code Playgroud)

现在我知道如何做其余的但是我被困在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!";
  }
}
Run Code Online (Sandbox Code Playgroud)

hak*_*kre 14

简单,请参阅strtr文档:

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

$message = strtr($message, $vars);
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法可以大大简化,您可以将整个模板传递给任何需要字符串输入的函数.

$vars = compact('username', 'message');
$message = new MessageTemplateFile('email.tpl', $vars);
Run Code Online (Sandbox Code Playgroud)