www.ThimbleOpenSource.com

Split PHP file to PHP code and inline HTML using token_get_all


For my upcoming release of ThimbleFramework I needed a function that splits any PHP file to parts of inline HTML and PHP code. The result is array of HTML and PHP which can be safely joined to original PHP file.

function split_php_html($code) {
  $tokens = token_get_all($code);
  $output = array();
  $tmp = '';
  foreach ($tokens as $token) {
    if (is_array($token)) {
      if ($token[0] === T_INLINE_HTML) {
        if ($tmp!='') $output[] = $tmp;
        $output[] = $token[1];
        $tmp = '';
      } else {
        $tmp .= $token[1];
      }
    } else {
      $tmp .= $token;
    }
  }
  if ($token[0] !== T_INLINE_HTML) $output[] = $tmp;
  return $output;
}