* $engine->render('This is {a} and these are {c.0%E} and {c.1}', ['a' => 'b', 'c' => [1, 'e']]); * //Prints "This is b and these are d and 1.000000E+0" * */ class SprintfEngine extends Engine { /** * {@inheritdoc} */ public function render($template, $value) { //Performance: if there are no '%' fallback to Engine if (strstr($template, '%') == false) { return parent::render($template, $value); } $result = $template; if (!is_array($value)) $value = array('' => $value); foreach (new NestedKeyIterator(new RecursiveArrayOnlyIterator($value)) as $key => $value) { $pattern = "/" . $this->left . $key . "(%[^" . $this->right . "]+)?" . $this->right . "/"; preg_match_all($pattern, $template, $matches); $substs = array_map(function ($match) use ($value) { return $match !== '' ? sprintf($match, $value) : $value; }, $matches[1]); $result = str_replace($matches[0], $substs, $result); } return $result; } }