DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Replace Text Template For Parameter Hash Table

  • submit to reddit

Replace text template for parameter hash table

$mytext = 'Hi, my name is {%name%}, and my address is {%address%}';
rep_templates($mytext, array('name'=>'Steven', 'address'=>'Rua Beira Mar, 12'));
print $text; //Output: Hi, my name is Steven, and my address is Rua Beira Mar, 12

Other ex.

$row = mysql_fetch_assoc($my_result_from_query);

$mytext = file_get_contents('./text_for_email_template.txt');

rep_templates($mytext, $row);

sendmail($row['email', 'Subject:Hi mane!', $mytext);

function rep_templates(&$t, $d){
    preg_match_all ( '/{\%(\w*)\%\}/' , $t , $matches );
    foreach($matches[1] as $m){
            $pattern = "/{\%".$m."\%\}/";
            $t = preg_replace( $pattern, $d[$m], $t);