Extract method call from string

How to extract method name and argument from a string code?

Example :

$obj->MethodA($obj->MethodB(param1,$obj->MethodX()))

I tried using this regex but not work

preg_match_all('/\$obj->(\w+)\(((\w|,| )*)\)/', $string, $matches)

The aim is to extract all the method calls as well as their arguments, so the matches should match

$obj->MethodA($obj->MethodB(param1, $obj->MethodX()))
$obj->MethodB(param1,$obj->MethodX())
$obj->MethodX()

Some people might say using regex is not ideal. Is there any alternative?


I would recommend using something that understands PHP's syntax. For example this library - https://github.com/nikic/PHP-Parser

Regex would probably get unwieldy pretty fast.

Quick example using the mentioned PHP-Parser.

use PhpParser\Node\Expr\CallLike;
use PhpParser\NodeFinder;
use PhpParser\ParserFactory;
use PhpParser\PrettyPrinter\Standard;

$php = '<?php $obj->MethodA($obj->MethodB("test",$obj->MethodX()));';

$parserFactory = new ParserFactory();
$parser = $parserFactory->create(ParserFactory::PREFER_PHP7);

$statements = $parser->parse($php);

$finder = new NodeFinder();

// Or if you only want method calls, we could also find instances of MethodCall
$calls = $finder->findInstanceOf($statements, CallLike::class);

$printer = new Standard();
foreach ($calls as $call) {
    echo $printer->prettyPrintExpr($call) , "\n";
}

// Output
//$obj->MethodA($obj->MethodB("test", $obj->MethodX()))
//$obj->MethodB("test", $obj->MethodX())
//$obj->MethodX()