Tolerant PHP Parser PHP 解析器开源项目

我要开发同款
匿名用户2017年01月29日
42阅读
开发技术PHP
所属分类开发工具、语法解析工具
授权协议MIT

作品详情

这是一个早期的PHP解析器,相当于实现了PHP对PHP脚本的解析。

示例代码:

<?php// Autoload required classesrequire "vendor/autoload.php";// Instantiate new parser instance$parser = new PhpParser\Parser();// Return and print an AST from string contents$astNode = $parser->parseSourceFile('<?php /* comment */ echo "hi!"');var_dump($astNode);// Gets and prints errors from AST Node. The parser handles errors gracefully,// so it can be used in IDE usage scenarios (where code is often incomplete).$errors = PhpParser\Utilities::getDiagnostics($astNode);var_dump(iterator_to_array($errors));// Traverse all Node descendants of $astNodeforeach ($astNode->getDescendantNodes() as $descendant) {    if ($descendant instanceof \PhpParser\Node\StringLiteral) {        // Print the Node text (without whitespace or comments)        var_dump($descendant->getText());        // All Nodes link back to their parents, so it's easy to navigate the tree.        $grandParent = $descendant->getParent()->getParent();        var_dump($grandParent->getNodeKindName());        // The AST is fully-representative, and round-trippable to the original source.        // This enables consumers to build reliable formatting and refactoring tools.        var_dump($grandParent->getLeadingCommentAndWhitespaceText());    }    // In addition to retrieving all children or descendants of a Node,    // Nodes expose properties specific to the Node type.    if ($descendant instanceof \PhpParser\Node\Expression\EchoExpression) {        $echoKeywordStartPosition = $descendant->echoKeyword->getStartPosition();        // To cut down on memory consumption, positions are represented as a single integer         // index into the document, but their line and character positions are easily retrieved.        $lineCharacterPosition = \PhpParser\Utilities::getLineCharacterPositionFromPosition(            $echoKeywordStartPosition        );        echo "line: $lineCharacterPosition->line, character: $lineCharacterPosition->character";    }}
查看全文
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论