Parsing and Printing PHP Code

2020-04-17 04:53发布

Preferably I'd like a solution which allows me to parse PHP from PHP, but any solution is welcome. (As an example of what I'm looking for, Ruby has the - amongst others - ruby_parser gem.)


Edit:

I am looking to generate abstract syntax trees of some kind, from PHP code. (And unless I am mistaken, I am fully aware of the existence and behaviour of the eval function.)

What are the options (if any) for parsing PHP code to some sort of abstract syntax tree? And what are the options for turning these syntax trees back into (readable) PHP code?

标签: php parsing
3条回答
干净又极端
2楼-- · 2020-04-17 05:15

You are looking for the evil of eval() I believe.

http://php.net/manual/es/function.eval.php

查看更多
Ridiculous、
3楼-- · 2020-04-17 05:22

Edit: this answer was written before @pepjin edited their question and changed the requirements. See comments for context.


eval() to execute PHP code from within PHP.

To analyse PHP code for your own micro language etc you can use the PHP Tokenizer. List of parser tokens: http://www.php.net/manual/en/tokens.php

查看更多
劳资没心,怎么记你
4楼-- · 2020-04-17 05:29

A tokenizer is not the same as a parser. The tokenizer just produces tokens and not in a tree format. For those who are actually looking to produce an AST for PHP similar to what ruby_parser does for Ruby, use the PHP-Parser project (https://github.com/nikic/PHP-Parser).

The PHP-Parser project also comes with a pretty printer that turns your AST back to PHP.

查看更多
登录 后发表回答