0

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?

8
  • 1
    The 3rd parameter of preg_match stores what is captured. Commented Feb 26, 2016 at 2:22
  • @chris85 thanks for comment. Edited the question Commented Feb 26, 2016 at 2:25
  • So you want to match $funcName in the string? Your current regex has an or there. You also are using a non-capture group but I think you do want to capture part of this.. Commented Feb 26, 2016 at 2:28
  • 1
    So maybe, eval.in/525839? Commented Feb 26, 2016 at 2:36
  • 1
    Your code actually worked you just had a typo, eval.in/525841. myFuncString != $myFuncString. Commented Feb 26, 2016 at 2:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. It returns [[0] => FooBar("Arg1, Arg2") [1] => Arg1, Arg2], how can only get the arguments with doubles quotes ('"Arg1, Arg2"') and not the function name?
You should make the .* not greedy. If there were ") later on this line it would match until the last occurrence.
@Wistar You echo $res[1]. @chris85 that is a good suggestion, my code assumes that that there aren't anymore (). The only time I see that is in minified/encoded php files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.