diff --git a/phpBB/phpbb/template/twig/lexer.php b/phpBB/phpbb/template/twig/lexer.php
index 7ab569313c..bd9ece57fd 100644
--- a/phpBB/phpbb/template/twig/lexer.php
+++ b/phpBB/phpbb/template/twig/lexer.php
@@ -75,7 +75,7 @@ class phpbb_template_twig_lexer extends Twig_Lexer
 
 		// Fix tokens that may have inline variables (e.g. <!-- DEFINE $TEST = '{FOO}')
 		$code = $this->fix_inline_variable_tokens(array(
-			'DEFINE.+=',
+			'DEFINE \$[a-zA-Z0-9]+ =',
 			'INCLUDE',
 			'INCLUDEPHP',
 			'INCLUDEJS',
@@ -240,7 +240,7 @@ class phpbb_template_twig_lexer extends Twig_Lexer
 			return "<!-- {$matches[1]}IF{$inner}-->";
 		};
 
-		return preg_replace_callback('#<!-- (ELSE)?IF((.*)[\s][\$|\.|!]([^\s]+)(.*))-->#', $callback, $code);
+		return preg_replace_callback('#<!-- (ELSE)?IF((.*?)[\s][\$|\.|!]([^\s]+)(.*?))-->#', $callback, $code);
 	}
 
 	/**
@@ -264,10 +264,10 @@ class phpbb_template_twig_lexer extends Twig_Lexer
 		*/
 
 		// Replace <!-- DEFINE $NAME with {% DEFINE definition.NAME
-		$code = preg_replace('#<!-- DEFINE \$(.*)-->#', '{% DEFINE $1 %}', $code);
+		$code = preg_replace('#<!-- DEFINE \$(.*?) -->#', '{% DEFINE $1 %}', $code);
 
 		// Changing UNDEFINE NAME to DEFINE NAME = null to save from creating an extra token parser/node
-		$code = preg_replace('#<!-- UNDEFINE \$(.*)-->#', '{% DEFINE $1= null %}', $code);
+		$code = preg_replace('#<!-- UNDEFINE \$(.*?)-->#', '{% DEFINE $1= null %}', $code);
 
 		// Replace all of our variables, {$VARNAME}, with Twig style, {{ definition.VARNAME }}
 		$code = preg_replace('#{\$([a-zA-Z0-9_\.]+)}#', '{{ definition.$1 }}', $code);
diff --git a/tests/template/template_test.php b/tests/template/template_test.php
index f2e3903458..e64493e59a 100644
--- a/tests/template/template_test.php
+++ b/tests/template/template_test.php
@@ -158,7 +158,7 @@ class phpbb_template_template_test extends phpbb_template_template_test_case
 				array(),
 				array('test_loop' => array(array(), array(), array(), array(), array(), array(), array()), 'test' => array(array()), 'test.deep' => array(array()), 'test.deep.defines' => array(array())),
 				array(),
-				"xyz\nabc\n\$VALUE == 'abc'abc\nbar\nbar\nabc\ntest!@#$%^&*()_-=+{}[]:;\",<.>/?\n[]",
+				"xyz\nabc\n\$VALUE == 'abc'abc\nbar\nbar\nabc\ntest!@#$%^&*()_-=+{}[]:;\",<.>/?\n[]|foobar|",
 			),
 			array(
 				'define_advanced.html',
diff --git a/tests/template/templates/define.html b/tests/template/templates/define.html
index e6c8ef49c9..f519078a5b 100644
--- a/tests/template/templates/define.html
+++ b/tests/template/templates/define.html
@@ -16,3 +16,4 @@ $VALUE == 'abc'
 {$VALUE}
 <!-- DEFINE $VALUE = '' -->
 [{$VALUE}]
+<!-- DEFINE $TEST -->foobar<!-- ENDDEFINE -->|{$TEST}|