teelou teelou - 2 months ago 18
Twig Question

PHP how to read comments from twig file?

How can I read comments in twig files using PHP?

test.twig:

{# Holy cow Twig is awesome! #}


PHP:

$tokens = token_get_all(file_get_contents("test.twig"));
$comments = array();
foreach($tokens as $token) {
if($token[0] == T_COMMENT || $token[0] == T_DOC_COMMENT) {
$comments[] = $token[1];
}
}
print_r($comments);


Result:

Array ( )


Any ideas?

Answer

why not use regex?

$txt = file_get_contents("test.twig");
if ( preg_match_all ("/{#([^}]*)#}/", $txt, $matches) )
  print_r($matches[1]);