Preg_match_all & str_replace
Instead of relying on preg_replace_callback, we can also do the matching and replacing ourselves. In this method, we first search all placeholders, determine what to replace them with and then replace all of them. This method is slightly less efficient and elegant than the preg_replace_callback method.
To search for all placeholder patterns, we use the following code:
preg_match_all('/{([^}]*)}/', $template, $matches);This will put an array in $matches which contains all the matches. The contents of this array are a little strange: The first element of the array contains an array with all full matches. The second element contains the first group of each match, and so on. So the match $matches[0][1] contains the group $matches[1][1]. An example:
Array ( [0] => Array ( [0] => {planet} [1] => {name} ) [1] => Array ( [0] => planet [1] => name ) )
To determine the replacement string, we step through $matches[1] and put the original string and the replacement string in an array. We then pass that array to str_replace, in a form that it can understand:
$data = array('planet' => 'World', 'name' => 'Wiebe'); $template = 'Hello {planet}. My name is {name}.'; preg_match_all('/{([^}]*)}/', $template, $matches); foreach ($matches[1] as $key) { $replacements['{'.$key.'}'] = $data[$key]; } echo str_replace(array_keys($replacements), array_values($replacements), $template);The array $replacements contains placeholder tags as keys and replacement strings as data. We pass that to str_replace, thus replacing all placeholders with the corresponding data.