3v4l.org

run code in 300+ PHP versions simultaneously
<?php function template($template, $vals) { $matches = array(); $regex = "/\{\{(\S+)\}\}/e"; $rendered = $template; // in case no matches are found preg_match_all($regex, $template, $matches, PREG_OFFSET_CAPTURE, 3); foreach ($matches[0] as $found) { $block = $found[0]; $offset = $found[0]; $k = str_replace('{{', '', $block); $k = str_replace('}-}', '', $k); $rendered = preg_replace($regex, '$vals[\\1]', $template); } return $rendered; } function template2($template, $vals) { $matches = array(); $regex = "/\{\{(\S+)\}\}"; $rendered = $template; // in case no matches are found preg_match_all($regex, $template, $matches, PREG_OFFSET_CAPTURE, 3); foreach ($matches[0] as $found) { $block = $found[0]; $offset = $found[0]; $k = str_replace('{{', '', $block); $k = str_replace('}-}', '', $k); $rendered = preg_replace_callback($regex, function($matches) { return $matches[0]; }, $template); } return $rendered; } $template = "test {{ME}}."; $vals = array('ME' => 'beep'); echo template2($template, $vals);
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
Warning: preg_match_all(): No ending delimiter '/' found in /in/BcZDq on line 30 Warning: Undefined array key 0 in /in/BcZDq on line 32 Warning: foreach() argument must be of type array|object, null given in /in/BcZDq on line 32 test {{ME}}.
Output for 5.5.24 - 5.5.35, 5.6.8 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.10, 7.2.0 - 7.2.33, 7.3.16 - 7.3.31, 7.4.0 - 7.4.33
Warning: preg_match_all(): No ending delimiter '/' found in /in/BcZDq on line 30 Notice: Undefined offset: 0 in /in/BcZDq on line 32 Warning: Invalid argument supplied for foreach() in /in/BcZDq on line 32 test {{ME}}.
Output for 7.3.32 - 7.3.33
Warning: preg_match_all(): No ending delimiter '/' found in /in/BcZDq on line 30 Warning: Invalid argument supplied for foreach() in /in/BcZDq on line 32 test {{ME}}.

preferences:
175.87 ms | 402 KiB | 181 Q