Jump to content

Email templates, variable replacement


versatilewt

Recommended Posts

Here's what I'm trying to do

 

Right now I have a bunch of "template" email responses stored in my DB, which are used frequently. Basically, what I'd like to do is for the templates, store things like ##CUSTOMER_NAME## and ##PRODUCT_NAME## in them. Then, when emailing, I'd like to pass an array of data (like, array("CUSTOMER_NAME"=>"Bob, "PRODUCT_NAME"=>"Widget") or whatever, depending on the particular email. There are also some basic if statements I want to execute, like if ##STATE## of customer == my state, say we'll charge you sales tax, or if ##STATE## in_array("CA", "WA", "OR") say "west coast" or something.

 

I'm guessing it would involve preg_replace and some for loops, but I'm not sure the most efficient way to go about this.

 

Any advice/suggestions appreciated. Thanks.

Link to comment
https://forums.phpfreaks.com/topic/154305-email-templates-variable-replacement/
Share on other sites

Okay had some time to write some code for an example :)

<?php
header('Content-type: text/plain');
$msg = "Hey ##CUSTOMER_NAME##,
This is in reference to ##PURCHASE_PRODUCT## purchased on ##PURCHASE_DATE##.
This is to confirm we will be sending it to
##CUSTOMER_ADDRESS##
##CUSTOMER_CITY##, ##CUSTOMER_STATE## ##CUSTOMER_ZIP##";

// bogus entry entry (this is where ya wud call customer/purchase info

$customer = array(
    'name' => 'John Doe',
    'address' => '123 Happy Ln',
    'city' => 'Sunny',
    'state' => 'CA',
    'zip' => '99999'
);
$purchase = array(
    'date' => '9/9/09',
    'product' => 'php tutorials',
    'quantity' => '50'
);

function my_vars($matches)
{
    global $customer, $purchase;
    
    $main=strtolower($matches[1]); // Get our Array Variable name
    $sub=strtolower($matches[2]);  // Get our Array Element Name
    $var=$$main;  // Map to our Array Variable
    if(isset($var[$sub])) // Does the Array Element exist?
    {
        $ret = $var[$sub]; // Return the Element
    } else {
        $ret = $matches[0]; // Return original pattern
    }
    // Conditional Example
    if($main=='customer' && $sub=='state' && $ret=='CA') $ret = 'California';
    
    return $ret;
}

header('Content-type: text/plain');
echo preg_replace_callback('/##(\w+)?_(\w+)##/','my_vars',$msg);
?>

 

Output:

Hey John Doe,

This is in reference to php tutorials purchased on 9/9/09.

This is to confirm we will be sending it to

123 Happy Ln

Sunny, California 99999

 

:) Told ya simple :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.