Php 如何使用递归PCRE正则表达式匹配嵌套css?

Php 如何使用递归PCRE正则表达式匹配嵌套css?,php,regex,pcre,recursive-regex,Php,Regex,Pcre,Recursive Regex,我尝试使用递归PCRE php正则表达式从嵌套css代码(字符串)恢复单个结果: 但是,使用当前的正则表达式,我无法做到这一点:( 出于教学/学习目的,我确实需要使用(?R)来获得这些匹配项 我怎样才能做到这一点?请查看,了解如何在没有正则表达式的情况下以编程方式实现它。对不起,MonkeyZeus,但我确实需要使用正则表达式进行教学。我个人不熟悉递归,但似乎高度相关。PCREs递归子匹配无法通过PHP接口捕获。请尝试preg\u match\u all('~^[^{}\n]*({((?:[^{

我尝试使用递归PCRE php正则表达式从嵌套css代码(字符串)恢复单个结果:

但是,使用当前的正则表达式,我无法做到这一点:(

出于教学/学习目的,我确实需要使用(?R)来获得这些匹配项


我怎样才能做到这一点?

请查看,了解如何在没有正则表达式的情况下以编程方式实现它。对不起,MonkeyZeus,但我确实需要使用正则表达式进行教学。我个人不熟悉递归,但似乎高度相关。PCREs递归子匹配无法通过PHP接口捕获。请尝试
preg\u match\u all('~^[^{}\n]*({((?:[^{}]+++|(?1))*)}~m',$text$matches);print\r($matches[2]);
<?php

//no recursive
$string = '{ color: #888; }';
$regex  = "/\{(.+)\}/";
preg_match_all($regex, $string, $matches);
var_dump($matches);

//attempt to be recursive
$pattern = '/{(?:[^{}]+|(?R))*}/';
$string = "
body { color: #888; }

@media print { body { color: #333; } }

code { color: blue; }
";
$regex  = "/\{(.+|(?R))\}/";
preg_match_all($regex, $string, $matches);
var_dump($matches);
array(4) {
  [0]=>
  string(12) "color: #888;"
  [1]=>
  string(21) "body { color: #333; }"
  [2]=>
  string(12) "color: #333;"
  [3]=>
  string(12) "color: blue;"
}