自动解析 PHP 以将 PHP 代码与 HTML 分开 [英] Automatically parsing PHP to separate PHP code from HTML

查看:35
本文介绍了自动解析 PHP 以将 PHP 代码与 HTML 分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理大型 PHP 代码库;我想将 PHP 代码与 HTML 和 JavaScript 分开.(我需要在 PHP 代码上做几次自动搜索和替换,在 HTML 上做不同的搜索和替换,在 JS 上做不同的).有没有一个好的解析器引擎可以为我分离出 PHP?我可以使用正则表达式来做到这一点,但它们并不完美.也许我可以在 ANTLR 中构建一些东西,但最好是已经存在的好的解决方案.

I'm working on a large PHP code base; I'd like to separate the PHP code from the HTML and JavaScript. (I need to do several automatic search-and-replaces on the PHP code, and different ones on the HTML, and different on the JS). Is there a good parser engine that could separate out the PHP for me? I could do this using regular expressions, but they're not perfect. I could build something in ANTLR, perhaps, but a good already existing solution would be best.

我应该说清楚:我不想要或不需要完整的 PHP 解析器.只需要知道给定的令牌是否是:- PHP 代码- PHP 单引号字符串- PHP 双引号字符串- PHP 注释- 不是 PHP,而是 HTML/JavaScript

I should make clear: I don't want or need a full PHP parser. Just need to know if a given token is: - PHP code - PHP single quote string - PHP double quote string - PHP Comment - Not PHP, but rather HTML/JavaScript

推荐答案

tokenizer 内置于 PHP 本身?

How about the tokenizer built right into PHP itself?

分词器函数提供了一个PHP 标记器的接口嵌入在 Zend 引擎中.使用这些函数你可以自己写PHP源码分析或修改工具而无需处理词法上的语言规范水平.

The tokenizer functions provide an interface to the PHP tokenizer embedded in the Zend Engine. Using these functions you may write your own PHP source analyzing or modification tools without having to deal with the language specification at the lexical level.

您在评论中询问是否可以从标记化的输出中重新生成代码 - 但是您可以,所有空格都保留为 T_WHITESPACE 标记.以下是将标记化输出转回代码的方法:

You ask in the comments whether you can regenerate the code from the tokenized output - yet you can, all whitespace is preserved as T_WHITESPACE tokens. Here's how you might turn the tokenized output back into code:

$regenerated='';

$tokens = token_get_all($code);
foreach($tokens as $idx=>$t)
{
    if (is_array($t))
    {

         //do something with string and comments here?
         switch($t[0])
         {
             case T_CONSTANT_ENCAPSED_STRING:
                  break;
             case T_COMMENT:
             case T_DOC_COMMENT:
                 break;

         }
         $regenerated.=$t[1];


    }
    else
    {
         $regenerated.=$t;
    }
}

这篇关于自动解析 PHP 以将 PHP 代码与 HTML 分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆