Over a million developers have joined DZone.

Replace Text Template For Parameter Hash Table

DZone's Guide to

Replace Text Template For Parameter Hash Table

· ·
Free Resource

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);

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}