Over a million developers have joined DZone.

Replace Text Template For Parameter Hash Table

·
/*

Replace text template for parameter hash table

Ex:
$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){
        if($d[$m]!=null){
            $pattern = "/{\%".$m."\%\}/";
            $t = preg_replace( $pattern, $d[$m], $t);
        }
    }
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}