PHP Regex capture repeated children as groups inside parent pattern

I want to capture a repeated values wrapped by parentheses within parents.

(parent (foo 25) (bar 500) (child (100 10) (300 20) (400 30)))
(parent (foo 80) (bar 130) (child (200 15)))

knowing every child can contain one or multiple children (child (..) ..) or (child (..) (..) (..) ..)

formatted:

(parent
    (foo 25)
    (bar 500)
    (child
        // want to capture the below children dynamically (the integers only)
        (100 10)
        (300 20)
        (400 30)
    )
)

// without conflicting with other values in same file
(extra (foo 18) (bar 77))
(different (foo 46) (bar 190))

The output i’m trying to get:

Array(
    '100 10',
    '300 20',
    '400 30'
)

not sure to include things i’ve tried, they’re all wasn’t for what i need.

How can i achieve that?

>Solution :

Assuming the elements (100 10) would only occur as children, then a regex find all approach might be viable here:

$input = "(parent (foo 25) (bar 500) (child (100 10) (300 20) (400 30)))";
$input = preg_replace("/\(parent (?:\((?!\bchild\b)\w+.*?\) )*/", "", $input);
preg_match_all("/\((\d+ \d+)\)/", $input, $matches);
print_r($matches[1]);

This prints:

Array
(
    [0] => 100 10
    [1] => 300 20
    [2] => 400 30
)

Leave a Reply