6 August, 2013 — Development, Snippets

Simple PHP Template Class

Update: Now available on GitHub here. Please commit improvements.

For a recent project of mine (newsletter system) I needed a simple but effective PHP class that would allow me to send a string of data and find every word with the curly bracket around it and replace it with a word or string.

For example in my newsletter system, I needed the email’s to be customized to the person it would be sending it to such as Dear Daniel… Dear James…. but during the loop to send the email I would need to get the script to switch {name} to be Daniel. To do this I found this amazing little PHP class that does just the job.

Download

Click here to download Simple PHP Template Class.

The Usage

This class is very simple. You pass 3 variables into the function Replace.

  1. An array of keys and variables – the key will be what the script will look for in your template such as {name}. The value will be what {name} will be replaced with.
  2. The template string where the data will be replaced.
  3. If the template is case sensitive. Eg {Name} wouldn’t work in the below example where as {name} would.
// Array of variables to change, template string, case sensitive true/false
echo CurlyVariables::Replace(array('name' => $name, 'email' => $email), $string, true);

Any trouble please let me know in the comments below.

Photo by: Travis Isaacs