celsowm
celsowm

Reputation: 404

How to use recursive PCRE regex to match nested css?

I am trying to use recursive PCRE php regex to recover individual results from nested css codes (strings):

<?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);

The expected result would be something like:

array(4) {
  [0]=>
  string(12) "color: #888;"
  [1]=>
  string(21) "body { color: #333; }"
  [2]=>
  string(12) "color: #333;"
  [3]=>
  string(12) "color: blue;"
}

But, with this current regex I was not able to do that :(

For teaching/study purpose, I do need to use (?R) to get those matches.

How can I achieve this?

Upvotes: 0

Views: 152

Answers (0)

Related Questions