Last Updated: May 31, 2021
·
596
· nrutman

Easy Templating in PHP

I recently had a project where I needed to do some basic string / data merging (i.e. templating) that went beyond PHP's baked-in functions (sprintf, str_replace, preg_replace, etc.). While there are already fantastic templating libraries available, my needs were minimal and I wanted to avoid adding a larger component to the codebase but still let me be DRY.

After some string replacement performance research, I decided that str_replace should do the heavy lifting...and here's what I came up with:

https://gist.github.com/4372785

The comments in the gist have a more complex example that shows the limitations of PHP's built-in functions. Here's a simpler example, just to demonstrate the concept:

$tempData = array(
    'name' => 'Joe Smith',
    'occupation' => 'Speech Therapist'
);
echo renderTemplate('Hello, my name is %name% and I am a %occupation%.');

// prints: Hello my name is Joe Smith and I am a Speech Therapist.

Again, I wouldn't want to write a whole application with this system, but for websites or small apps that need some on-demand templating abilities, it's a nice one-function solution.