PHPLOVER PHPLOVER - 6 months ago 32
PHP Question

replace multiple placeholders with php?

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. 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 there 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.

I hope i have not confused anyone, i struggle quite bad when it comes to explaining and i end up going on and on, so i do apologize in advance.

Heres my function that i kept going on about above, hopefully it will explain better. 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!";
}
}


Thanks for any help
phplover

Answer

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