PHP 正则表达式捕获在 parent 模式中重复 children 作为组
PHP Regex capture repeated children as groups inside parent pattern
我想捕获 parents.
中用括号括起来的重复值
(parent (foo 25) (bar 500) (child (100 10) (300 20) (400 30)))
(parent (foo 80) (bar 130) (child (200 15)))
知道每个child可以包含一个或多个children (child (..) ..)
或(child (..) (..) (..) ..)
格式化:
(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))
我试图获得的输出:
Array(
'100 10',
'300 20',
'400 30'
)
不确定是否包含我尝试过的内容,它们都不是我需要的。
我怎样才能做到这一点?
假设元素 (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]);
这会打印:
Array
(
[0] => 100 10
[1] => 300 20
[2] => 400 30
)
我想捕获 parents.
中用括号括起来的重复值(parent (foo 25) (bar 500) (child (100 10) (300 20) (400 30)))
(parent (foo 80) (bar 130) (child (200 15)))
知道每个child可以包含一个或多个children (child (..) ..)
或(child (..) (..) (..) ..)
格式化:
(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))
我试图获得的输出:
Array(
'100 10',
'300 20',
'400 30'
)
不确定是否包含我尝试过的内容,它们都不是我需要的。
我怎样才能做到这一点?
假设元素 (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]);
这会打印:
Array
(
[0] => 100 10
[1] => 300 20
[2] => 400 30
)