2

I would like to parse between { and }, . I searched and already tried many solutions from stackoverflow but not all seems to be working.

The best solution worked for me is Extracting all values between curly braces regex php but it fails when there are nested curly braces. I tried {\K[^}]*(?=},) eg: Id: 1181 doesn't match.

Sample Data

{
    Id: 1180
    Name: "ABCD"
    Type: 1
    Json: <"
        Some sample data
    ">
},
{
    Id: 1181
    Name: "EFGH"
    Type: 4
    More: Value
    More: Value
    Json: <"
        Some sample data "{ with more curly braces }" and "{ more curly braces }";
    ">
},
{
    Id: 1182
    Name: "IJKL"
    Type: 2
    Json: <"
        Some sample data
    ">
},

Sublime result Result

Rahul Dev
  • 175
  • 1
  • 15

2 Answers2

2

You can use this recursive regex in PHP:

$regex = '/ { ( (?: [^{}]* | (?R) )* ) } /x';

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Without a specification of this format, there's no clean solution to parse the input. Using regex only partly help you, as there could be practical anything inside the "Json" field.

If you need a quick and dirty solution, you could use the fact, that the curlies are at the start of the line.

$m = preg_split('~^},$~m', $data);

or

preg_match_all('/\{.*?^\},$/ms', $str, $matches, PREG_SET_ORDER);

From there on, you could process the data however you like.

Philipp
  • 15,377
  • 4
  • 35
  • 52