Search code examples
phpregexfunctionpreg-match

PHP Regex preg_match arguments from a specific function name


Let's say I have

$funcName = 'FooBar';
$myFuncString = $funcName.'("Arg1, Arg2")';

How could I preg_match() so it returns "Arg1, Arg2" (with doubles quotes and without $funcName?

I have tried:

$pattern = '/(?:'.$funcName.'|\".*?)\"/';
preg_match($pattern, myFuncString, $matches);

It returns "Arg1, Arg2" even if $funcName does not match. Any suggestions?


Solution

  • This should work:

    $funcName = 'FooBar';
    $myFuncString = $funcName.'("Arg1, Arg2")';
    
    //$funcName = 'NooBar';
    $pattern = '/'.$funcName.'\("(.*)"\)/';
    $matches = preg_match($pattern, $myFuncString, $res);
    
    echo $res[1];
    

    I had to add $res to the preg_match which has the results and correct the pattern.

    Demo: http://sandbox.onlinephpfunctions.com/code/6de9d1236b82339199a2c64e914b5ca5b80e4e77