3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Template { public $dir = ''; private $extension = 'php'; private $template = ''; private $parse; function __construct($dir = false, $extension = 'php') { if ($dir) { $this->dir = preg_replace('#/+$#', '', $dir); } else { $this->dir = $dir; } $this->extension = $extension; } public function load() { if (func_num_args() > 0) { $files = func_get_args(); foreach ($files as $file) { if (is_file($this->dir . '/' . $file . '.' . $this->extension)) { $this->template .= file_get_contents($this->dir . '/' . $file . '.' . $this->extension); } else { trigger_error('Шаблона ' . htmlspecialchars($file . '.' . $this->extension) . ' не существует.', E_USER_WARNING); } } } } public function clear() { $this->template = ''; return true; } private function parseInclude($template) { //Парсим блоки {include=file} $count = preg_match_all('/{include=([\w\/]+)}/i', $template, $match); if ($count > 0) { $count -= 1; for ($i = 0; $i <= $count; $i++) { $file = $this->dir . '/' . $match[1][$i] . '.' . $this->extension; if (is_file($file)) { $template = str_replace($match[0][$i], $this->parseInclude(file_get_contents($file)), $template); } else { $template = str_replace($match[0][$i], '', $template); trigger_error('Ошибка вставки шаблона <b>' . htmlspecialchars($match[1][$i]) . '</b>. Шаблона <b>' . htmlspecialchars($file) . '</b> не существует.', E_USER_WARNING); } } } return $template; } private function parseBlock($parse, $template) { $c = preg_match_all('#\[([\w\-\!]+)\](.*?)\[/\1\]#is', $template, $match); if ($c > 0) { $c -= 1; for ($i = 0; $i <= $c; $i++) { if ($match[1][$i]{0} == '!') { if (isset($parse[substr($match[1][$i], 1)])) $match[2][$i] = ''; } else { if (!isset($parse[$match[1][$i]])) $match[2][$i] = ''; } $template = str_replace($match[0][$i], $match[2][$i], $template); } $template = $this->parseBlock($parse, $template); } return $template; } public function parse($parse) { if (empty($this->template)) { trigger_error('Шаблон не задан или он пустой.', E_USER_WARNING); } else { $this->parse = $parse; $template = $this->parseInclude($this->template); $template = $this->parseBlock($parse, $template); return preg_replace('#\{([a-z0-9\-_]*?)\}#Ssie', '( ( isset($parse[\'\1\']) ) ? $parse[\'\1\'] : \'\' );', $template); } } } ?>

preferences:
37.35 ms | 402 KiB | 5 Q