Cara menggunakan php parse number
This is a PHP parser written in PHP. Its purpose is to simplify static code analysis and manipulation. Documentation for version 5.x (in development; for running on PHP >= 7.1; for parsing PHP 7.0 to PHP 8.2, with limited support for parsing PHP 5.x). Documentation for version 4.x (stable; for running on PHP >= 7.0; for parsing PHP 5.2 to PHP 8.2). Documentation for version 3.x (unsupported; for running on PHP >= 5.5; for parsing PHP 5.2 to PHP 7.2). FeaturesThe main features provided by this library are:
Quick StartInstall the library using composer:
Parse some PHP code into an AST and dump the result in human-readable form:
use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;
$code = <<<'CODE'
function test($foo)
{
var_dump($foo);
}
CODE;
$parser = (new ParserFactory())->createForNewestSupportedVersion();
try {
$ast = $parser->parse($code);
} catch (Error $error) {
echo "Parse error: {$error->getMessage()}\n";
return;
}
$dumper = new NodeDumper;
echo $dumper->dump($ast) . "\n"; This dumps an AST looking something like this:
Let's traverse the AST and perform some kind of modification. For example, drop all function bodies: use PhpParser\Node; use PhpParser\Node\Stmt\Function_; use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; $traverser = new NodeTraverser(); $traverser->addVisitor(new class extends NodeVisitorAbstract { public function enterNode(Node $node) { if ($node instanceof Function_) { // Clean out the function body $node->stmts = []; } } }); $ast = $traverser->traverse($ast); echo $dumper->dump($ast) . "\n"; This
gives us an AST where the
Finally, we can convert the new AST back to PHP code: use PhpParser\PrettyPrinter; $prettyPrinter = new PrettyPrinter\Standard; echo $prettyPrinter->prettyPrintFile($ast); This gives us our original code, minus the
function test($foo)
{
} For a more comprehensive introduction, see the documentation. Documentation
Component documentation:
|