2

In creating automatic emails certain parts of the email need to be replaced with stored data.

eg. Dear %first_name% %surname%, Thanks for attending the %place_name%.

This could be done with a string replace for each of them, but there must be a faster method.

Assuming that the variable name is identical to what we want from the system eg. %first_name% should be replaced with $user['first_name'] etc....

Walrus
  • 19,801
  • 35
  • 121
  • 199

2 Answers2

2

You can utilise preg_replace_callback to replace keys between %'s with array values:

$fields = array('first_name' => 'Tim', 'place_name' => 'Canada');

$string = preg_replace_callback('/%(.+?)%/', function($arr) use($fields)
{
    $key = $arr[1];
    return array_key_exists($key, $fields) ? $fields[$key] : $arr[0];
}, $string);
  • clever use of closures, which requires the newer versions of PHP – Kristian Jul 30 '12 at 16:12
  • @Kristian: PHP 5.3, the version which the anonymous function syntax was introduced, was released 3 years ago. I wouldn't consider it newer, and I would hope everyone is upgraded to at least that version. –  Jul 30 '12 at 16:16
  • never underestimate the power of code / version requirements to forcefully slow down upgrades from happening – Kristian Jul 30 '12 at 16:27
2

One option:

$vars = array(
  'firstname' = 'Bob',
  'surname' = 'Dole',
  'place' = 'Las Vegas',
  // ...
);
extract($vars);
include('my_template.phtml');

And in my_template.phtml:

<?php
echo <<<EOF
    Dear $firstname $surname,<br>
    Thank you for attending the Viagra and Plantains Expo in $place.
EOF;
?>

If you're worried about name collisions while using extract(), you can always use the EXTR_PREFIX_ALL option, or one of the other extraction methods.

Or, better yet, don't reinvent the wheel. Just use Smarty or mustache.php.

See also this question: PHP template class with variables?

Community
  • 1
  • 1
Lèse majesté
  • 7,923
  • 2
  • 33
  • 44
  • +1 this is what I do with outputting views, and I recommend it – Kristian Jul 30 '12 at 16:12
  • @Kristian: Yea, CakePHP and probably a lot of other frameworks/libraries do it this way, albeit usually with additional features like output buffering and, in Cake 2.0, view blocks and view inheritance. – Lèse majesté Jul 30 '12 at 16:33