Home > php, Programming > Build a simple PHP template with str_replace()

Build a simple PHP template with str_replace()

You are given a task to notify a list of customers regarding their pin setting changes through their email address on file. There are many ways to accomplish this in PHP. One way I found quite interesting is through a simple php function str_replace. Let me demo through the following example (only showing how the message body is constructed, the email address part should be easy to take care of):

<?php
        /* main.php */
        function build_key($key) {
                return '{{'.$key.'}}';
        }

        function gen_msg($format_str, $arr) {
                $keys=array_map(build_key, array_keys($arr));
                // $keys can also be generated by using the following code
                // but I found using array_map is more elegant and fun
                // $keys=array();
                // foreach(array_keys($arr) as $k) {
                //      array_push($keys, '{{'.$k.'}}');
                // }

                return str_replace( $keys, array_values($arr), $format_str);
        }

        // here's the template
        $template="Dear {{user}}, your pin number has been changed to {{pin}}.";

        // here's the data, hard-coded in this example but it can be pulled from external sources as well
        $data=array(
                array( 'user'=>'John Smith', 'pin'=>'1234' ),
                array( 'user'=>'Mr. S', 'pin'=>'9999' ),
                array( 'user'=>'Customer', 'pin'=>'****' )
        );

        foreach($data as $d) {
                printf("%s\n", gen_msg($template, $d));
        }

Run the above code through php (cli) will output the following:

Dear John Smith, your pin number has been changed to 1234.
Dear Mr. S, your pin number has been changed to 9999.
Dear Customer, your pin number has been changed to ****.

[ Update ] I also added an OOP implementation of the above code, if you are interested you can checkout my code on github.

Advertisements
Categories: php, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: