tags:

views:

64

answers:

3

I have a pattern

ab 23 cde 25 ... and so on

Can I capture the above pattern like

array(
 [patterns] => array(
   [0] => array(
    [payer] => 'ab'
    [amt] => 23
   )
   [1] => array(
    [payer] => 'cde'
    [amt] => 25
   )
 )
)

Is this possible?

A: 

Form a regex to match each item in your array (\w+\s+\d+). Collect all of them (this should give you chunks like ab 23).

Then for each of these items, split on whitespace and cram into your larger array as [payer], [amt].

JoshD
I think you meant `\w+\s+\d+`. `\w*\s*\d*` will *always* match because it can legally match zero characters.
Alan Moore
@Alan Moore: Thank you :)
JoshD
+2  A: 

You can use preg_match_all for this as:

$str = 'ab 23 cde 25';
preg_match_all('/(\w+)\s+(\d+)/',$str,$matches);
$result = array();
for($i=0;$i<count($matches[0]);$i++) {
        $result[] = array('payer' => $matches[1][$i], 'amt' => $matches[2][$i]);
}

Working link

codaddict
Thanks. preg_match_all would do. Anyway this recurring pattern is part of a non-recurring pattern, so I guess anyway I would have to first get this recurring pattern out of it then run preg_match_all on it.
AppleGrew
A: 
(?:'|.)(\w+)(?:'|$)
tinifni