简体   繁体   English

PHP 正则表达式将重复的子项捕获为父模式内的组

[英]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 (..) (..) (..)..)知道每个孩子都可以包含一个或多个孩子(child (..)..)(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:我正在尝试获取 output:

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?我怎样才能做到这一点?

Assuming the elements (100 10) would only occur as children, then a regex find all approach might be viable here:假设元素(100 10)只会作为子元素出现,那么正则表达式查找所有方法在这里可能是可行的:

$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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM