Jump to content

Recommended Posts

Hi all,

 

So I'm setting up a system that has a lot of emails, and variable replacement within it, so I'm writing a class to manage some variable replacement for templates stored in the database.

 

Here's a brief example:

 

// template is stored in db, so that's how this would get loaded in
$template = "Hello, %customer_name%, thank you for contacting %website_name%";
// The array of replacements is built manually and passed to the class
// with actual values being called from db
$replacements = array('%customer_name%'=>'Bob', '%website_name%'=>'Acme');
$rendered = str_replace(array_keys($replacements), $replacements, $template);

 

Now, that works well and good for single var replacements, basic stuff. However, there are some places where there should be a for loop, and I'm lost how to implement it.

 

The idea is there'd be a template like this:

 

"hello, %customer_name%, thank you for requesting information on {products}"

 

Where, {products} would be an array passed to the template, which the is looped over for products requested, with a format like:

 

Our product %product_name% has a cost of %product_price%. Learn more at %product_url%.

So an example rendered version of this would be:

 

"hello, bob, thank you for requesting information on:

 

Our product WidgetA has a cost of $1. Learn more at http://example.com/A

 

Our product WidgetB has a cost of $2. Learn more at http://example.com/B

 

Our product WidgetC has a cost of $3. Learn more at http://example.com/C.

 

What's the best way to accomplish this?

A simple foreach should do the trick.

Something like:

 

<?php

// Get information
$products = array(
array("product_name", "price", "url"),
array("COD4 MW", "24.99", "/shop/products.php?id=3243164"),
array("COD4 MW2", "38.99", "/shop/products.php?id=3245235")
);

$customer_name = "John Doe";
$website_name = "www.SomeCart.com";

//Templates
$template_thankyou = "Hello %customer_name%, Thank you for your interest in these products at %website_name%:<br />%product_list%";
$template_product_list = "Our Product '%product_name%', for $%product_price%, For more information: <a href='%product_url%'>%product_url%</a><br />";

// We start with the lowest template (The one you would think you would "add" last, needs to be created first.)
$product_list = array();

// Loop for each product we want on the list (these product should be ni array like the one above)
foreach($products As $product_array){

// Add an array element (you can also use strings, but I find arrays faster and easier to understand/control)
$product_list[] = str_replace(
	array("%product_name%","%product_price%","%product_url%"),
	array($product_array[0],$product_array[1],$product_array[2]),
	$template_product_list
);
}

// This is because its an array we implode each element into a single string (seperated by \n new lines for readability)
$product_list = implode("\n", $product_list); // Implode the array into a single string (seperating with a Newline "\n", only visible in the HTML Source)

// Now we actually do the "Top-Level" replacement.
$page = str_replace(
array('%customer_name%','%website_name%','%product_list%'),
array($customer_name,$website_name,$product_list),
$template_thankyou
);

// Print results
exit($page);

?>

 

Hope this helps,

-cb-

Thanks ChemicalBliss,

 

The only thing is, I'm trying to have a generic class that can handle the simple cases and the variable case, and get the sub template out of the db if it's needed - and essentially examine the "replacements" array to see if it's necessary.

 

I was kind of envisioning passing something like:

 

array(

    '%customer_name%'=>'Bob',

    '%website_name%'=>'Acme',

    '%products%' = array(

        '0'=>array('%product_name%'=>'WidgetA', '%product_price%'=>'$1'),

        '1'=>array('%product_name%'=>'WidgetB', '%product_price%'=>'$2'),

        '2'=>array('%product_name%'=>'WidgetC', '%product_price%'=>'$3'),

    )

);

Yeah you could do that, it just means you will have to loop each array element and replace one by one.

But you need to get your templates somewhere (like passing as an argument).

 

<?php

$parameters = array(
    '%customer_name%'=>'Bob',
    '%website_name%'=>'Acme',
    '%products%' => array(
         array('%product_name%'=>'WidgetA', '%product_price%'=>'1'),
         array('%product_name%'=>'WidgetB', '%product_price%'=>'2'),
         array('%product_name%'=>'WidgetC', '%product_price%'=>'3'),
     )
);
$pkeys = array_keys($parameters);

$template_main = "Hello %customer_name%, Thank you for your interest in these products at %website_name%:<br />%products%";
$template_array = "Our Product '%product_name%', for $%product_price%, For more information: <a href='%product_url%'>%product_url%</a><br />";

// start with a template
$result = $template_main;

// Loop each parameter
foreach($parameters As $key => $value){

// Its a normal string, replace
if(!is_array($value)){
	$result = str_replace($key,$value,$result);
}else{
	$tempres = null;
	// Loop each array element (each template)
	foreach($value As $element){
		$temp = $template_array;

		// Loop each replacement value
		foreach($element As $key2 => $value2){
			$temp = str_replace($key2, $value2, $temp);
		}
		$tempres .= $temp; // Add replaced template to temp string
	}
	$result = str_replace($key, $tempres, $result); // replace with the temp string
}
}

exit($result);

?>

 

-cb-

 

PS: you can easily turn this into a function. but ke i said i would pass the templates in the argument as well.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.