0

We are developing a mail system, and we would like to allow user to add custom greeting while creating message.. for example, check following...

we will set this variable(var_name) in php.

Hello ${var_name},
This is test message.

we are not using any framework.

dogbane
  • 266,786
  • 75
  • 396
  • 414
seoppc
  • 2,766
  • 7
  • 44
  • 76

4 Answers4

3

What about str_replace?

$text = str_replace('${var_name}', $var_name, $text);
erenon
  • 18,838
  • 2
  • 61
  • 93
  • @seoppc str_replace even can take arrays as arguments, so you can fill all your variables at once. – Your Common Sense Feb 24 '11 at 08:35
  • i am getting a problem, its only replacing ${varname} with 1st entry of db inside of foreach loop. check following code... foreach($users as $user) { $content = str_replace('$name', $user['name'], $content); $msg = '
    '.$content.'
    ';
    – seoppc Feb 24 '11 at 11:52
1

I'd use PHP as the templating language it is:

Hello <?php echo $name; ?>,
This is a test message.

Then you can replace them like this:

function render($template, $vars = array()) {
    extract($vars, EXTR_SKIP);
    ob_start();
    include $template;
    return ob_get_clean();
}

echo render('email.tmpl', array('name' => 'Foo'));
deceze
  • 510,633
  • 85
  • 743
  • 889
-1

One way is to do the following:

Create a separate .php file for each email template, like so:

//email_text.php
Hello <?php echo $name ?>, <br/>
How are you doing?<br/>
Your truly,<br/>
<?php echo $author ?>

In the page which is sending the emails, you do something like this -

$name = 'Kevin';
$author = 'Freddy';  
ob_start();
include('email_text.php');
$output = ob_get_clean();
//$output now contains your email message with $name and $author substituted
Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
-1
$var_name = 'Powtac';

// ...

$template = "Hello ${var_name},
This is test message.";

echo $template;
powtac
  • 40,542
  • 28
  • 115
  • 170