phpregextemplatingpreg-replace-callbacktemplating-engine

Making a simple templating engine in PHP


I need to write a simple PHP function to replace text between {{ }} characters with their respective data.

Example:

String: "and with strange aeons even {{noun}} may {{verb}}"

$data = ['noun' => 'bird', 'verb' => 'fly'];

Result:

"and with strange aeons even bird may fly"

I have it almost working with the following code based on preg_replace_callback

function compile($str,$data){

    foreach ($data as $k => $v) {
        $pattern = '/\b(?<!\-)(' . $k . ')\b(?!-)/i';
        $str = preg_replace_callback($pattern, function($m) use($v){
            return $v;
        }, $str);
    }

    return $str;
}

But I cant seem to account for the {{ }}.

The result looks like this:

"and with strange aeons even {{bird}} may {{fly}}"

How can I adjust the regex and/or code to account for the double curly brackets?

Also, before anyone asks why I'm trying to do this manually rather than use PHP itself or the Smarty plugin -- its too narrow a use case to install a plugin and I cannot use PHP itself because the input string is coming in as raw text from a database. I need to compile that raw text with data stored in a PHP array.


Solution

  • Since you're looping anyway, keep it simple:

    foreach ($data as $k => $v) {
        $str = str_ireplace('{{'.$k.'}}', $v, $str);
    }
    

    You can add a space before {{ and after }} if needed.