Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading