1

Say I have the following string: Func(param1, param2) with an unknown number of params.
And I want to get the following array:

Array(
    [0] => Func(param1, param2),
    [1] => Func
    [2] => param1,
    [3] => param2,
    ...
)

I tried this:

$str = 'Func(param1, param2)';
preg_match('/^([a-z]+)\((?:([a-z0-9]+)\s*,?\s*)*\)$/i', $str, $matches);
print_r($matches);

And that is the output:

Array
(
    [0] => Func(param1, param2)
    [1] => Func
    [2] => param2
)

The sub pattern that captures the params captures only the last param. And I want it to capture all of the parameters.

Any ideas?

EDIT:
I know I can capture all of the params and then use explode. But that is not my question.
I want to know how it is done with regular expressions.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Idan Yadgar
  • 974
  • 1
  • 6
  • 16
  • 2
    I have to disapoint you, but what you want **isn't possible in PHP** and it's the same for almost every language [except Perl 6 and .NET](http://stackoverflow.com/a/6571139/). It's called **repeated capturing groups** and it was already asked [here](http://stackoverflow.com/q/6371226/) and [here](http://stackoverflow.com/q/6579908/). – HamZa Apr 29 '13 at 13:02
  • @HamZa DzCyberDeV Okay, thanks. – Idan Yadgar Apr 29 '13 at 13:12

2 Answers2

0

this should do it:

$str = 'Func(param1, param2, param32, param54, param293, par13am, param)';
preg_match_all("/(.*)[\(|\](.*)[,|\)]/U", $str, $match);

print_r($match[1]);
//output: Array ( [0] => Func [1] => param1 [2] => param2 [3] => param32 [4] => param54 [5] => param293 [6] => par13am [7] => param )
aleation
  • 4,796
  • 1
  • 21
  • 35
-1

You can get all params at once and then get an array from that string using explode:

$str = 'Func(param1, param2)';
preg_match('/^([a-z]+)\(([a-z0-9\,\s]+)\)$/i', $str, $matches);
print_r($matches);

$params = explode(',', str_replace(' ', '', $matches[2]));

print_r($params);
enenen
  • 1,967
  • 2
  • 17
  • 33
  • I know that. But my question is how I can do that without explode. – Idan Yadgar Apr 29 '13 at 12:30
  • Yes, I saw your edit. I will take a look but that was the very first thing which I thought about. Do you have а serious reason for not using explode? – enenen Apr 29 '13 at 12:31
  • 1
    No, but I wonder if there is a way to do that without using explode. – Idan Yadgar Apr 29 '13 at 12:36
  • I wanna know too :) My use-case isn't quite as simple, and I could really use a way to capture a repeating sub-pattern – Evert May 07 '13 at 16:13