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] : ''; }); }
These few lines of code allow me to create a very neat template system. The regular expression matches all the {{something}} lines inside the text variable, and the return function matches if something is inside the object data, and if so, it replaces it.
So,
text = "Hello {{var1}}, nice to meet {{var2}}"; data = { var1: "World", var2: "You" } //result => "Hello World, nice to meet You"
I am trying to replicate this functionality - this is PHP, but the only solution that comes to my mind is to use two cicles that parse each element of the data array, and the second inside the first that looks for the string inside Text.
Is there a cleaner way in php?
source share