In javascript you can define a return function when you do string replacements:
function miniTemplate(text, data) {
return text.replace(/\{\{(.+?)\}\}/g, function(a, b) {
return typeof data[b] !== 'undefined' ? data[b] : '';
});
}
This few lines of code allow me to create a very neat template system. The regular expression matches all the "{{something}}" strings inside the text variable and the return function matches if something is inside the object data, and if it is, it replaces it.
So,
text = "Hello {{var1}}, nice to meet {{var2}}";
data = { var1: "World", var2: "You" }
//result => "Hello World, nice to meet You"
Im trying to replicate this functionality is PHP, but the only solution that comes to my mind is using 2 cicles, one that parse each element of data array and the second one inside the first that looks for the string inside Text.
Is there a cleaner way in php?
preg_replace_callbackpreg_replace-callback(): php.net/manual/en/function.preg-replace-callback.php