3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Template { private $_template = ''; private $_assigns = array(); private $_prepared_code = null; const VALID_VARIABLE = '[a-zA-Z0-9_\x7f-\xff]*'; const TAG_SIGN_OPEN = '{'; const TAG_SIGN_CLOSE = '}'; public function __construct($template) { $this->_template = $template; } public function assign($name, $value) { $this->_assign($name, $value); } private function _assign($name, $value, array &$assigns = null) { if ($assigns == null) $this->_assigns[$name] = $value; else $assigns[$name] = $value; } public function assignArray($array) { $this->_assignArray($array); } private function _assignArray($array, array &$assigns = null) { foreach ($array as $name => $value) $this->_assign($name, $value, $assigns); } private function _getToken($string, $sign, $pos, &$token) { $position = strpos($string, $sign, $pos); if ($position === false) { $token = substr($string, $pos); $pos = false; } else { $token = substr($string, $pos, $position - $pos); $pos = $position + strlen($sign); } return $pos; } private function _prepareCode() { $prepared_code = '?' . '>'; $pos = 0; while ($pos !== false) { $pos = $this->_getToken($this->_template, self::TAG_SIGN_OPEN, $pos, $token); $prepared_code .= $token; if ($pos !== false) { $pos = $this->_getToken($this->_template, self::TAG_SIGN_CLOSE, $pos, $token); if ($pos === false) throw new Exception('Template syntax error. Expected "}"'); switch (true) { case preg_match('/^' . self::VALID_VARIABLE . '$/', $token): $prepared_code .= '<?php echo $assigns[\'' . $token . '\'] ?' . '>'; break; case preg_match('/^loop +(' . self::VALID_VARIABLE . ')$/', $token, $match): $prepared_code .= '<?php foreach ($assigns[\'' . $match[1] . '\'] as $__index => $__tmp)' . '{$this->_assignArray($__tmp, $assigns); unset($__tmp); ?' . '>'; break; case preg_match('/^end +loop$/', $token): $prepared_code .= '<?php } ?>'; break; case preg_match('/^\%index\%$/', $token): $prepared_code .= '<?php echo $__index ?' . '>'; break; default: throw new Exception('Template syntax error. Unexpected token "' . $token . '"'); break; } } } return $prepared_code; } public function getPreparedCode() { if ($this->_prepared_code === null) $this->_prepared_code = $this->_prepareCode(); return $this->_prepared_code; } private function _execute($prepared_code) { $assigns = $this->_assigns; ob_start(); eval($prepared_code); $content = ob_get_contents(); ob_end_clean(); return $content; } public function parse() { return $this->_execute($this->getPreparedCode()); } } $templateHtml = <<<END_HTML <div>{this}</div> {loop items} <div>{%index%}. {name}</div> {end loop} END_HTML; $template = new Template($templateHtml); $template->assign('this', 'test'); $template->assign('items', array( array('name' => 'First'), array('name' => 'Second') )); echo $template->parse();

preferences:
56.67 ms | 402 KiB | 5 Q