-->

更换用PHP多个占位符?(Replace multiple placeholders with PH

2019-06-23 13:25发布

我有一个送出的网站电子邮件(使用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!";
  }
}

Answer 1:

很简单,看strtr 文档

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

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

根据需要添加尽可能多(或更少)的更换对。 但我建议,你处理模板调用之前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;
    }
}

使用可大大简化的话,你可以将整个模板传递给需要字符串输入的任何功能。

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


Answer 2:

PHP的解决方案可以是:

  • 简单的用法%placeholder%更换机制:
    • str_replace
    • strtr
    • preg_replace
  • 使用纯PHP模板和条件逻辑的( 短的开放式标记在PHP和用于控制结构替换语法 )

请找到在Programmers.StackExchange宽答案找出关于PHP模板电子邮件其他方法。



Answer 3:

你为什么不只是使电子邮件模板PHP文件藏汉? 然后,你可以这样做:

Hello <?=$name?>, my name is <?=$your_name?>, today is <?=$date?>

里面的电子邮件生成的HTML,然后发送结果作为电子邮件。

在我看来,像你绕了艰辛的道路?



文章来源: Replace multiple placeholders with PHP?