1

I want to convert nested brackets to array with keywords. Here is pattern:

preg_match_all('/(?=\{((?:[^{}]++|\{(?0)\})++)\})/', $string, $res);

And data which need to parse:

 employee { 
    cashier { salary = 100; } 
    technician { age = 44; } 
 }

Result, that I need:

Array
    (
        [employee] => Array (
            [0] => Array
                (
                    [cashier] => Array
                        (
                            [salary] => 100
                        )

                )

            [1] => Array
                (
                    [technician] => Array
                        (
                            [age] => 44
                        )

                )
        )
    )

But cant iterate within nested brackets. Stucked here. Thanks in advance for your help

1
  • preg_split might be more suitable Commented May 9, 2017 at 7:34

1 Answer 1

2

You'll need a recursive approach here.

  1. First, analyze the outer structure with { and } on both sides.
  2. See, if we can find another nested structure
  3. If not, look for key = value pairs and return them

A regex demo for the outer structure can be found on regex101.com, a complete PHP demo would look as follows:

<?php

$string = <<<DATA
 employee { 
    cashier { salary = 100; } 
    technician { age = 44; } 
 }
DATA;

// regular expressions    
$outer = '~(?P<key>\w+)\s*(?P<value>\{(?:[^{}]*|(?R))*\})~';

// inner, key = value
$inner = '~(?P<key>\w+)\s*=\s*(?P<value>\w+)~';

function parse($string) {
    global $outer, $inner;
    $result = array();
    // outer
    preg_match_all($outer, $string, $matches, PREG_SET_ORDER);
    foreach ($matches as $match) {
        $result[$match["key"]] = parse(
            substr($match["value"], 1, -1)
        );
    }

    // if not found, inner structure
    if (!$matches) {
        preg_match_all($inner, $string, $matches, PREG_SET_ORDER);
        foreach ($matches as $match) {
            $result[$match["key"]] = $match["value"];
        }
        return $result;
    }
    return $result;
}

$result = parse($string);
print_r($result);
?>


This yields:

Array
(
    [employee] => Array
        (
            [cashier] => Array
                (
                    [salary] => 100
                )

            [technician] => Array
                (
                    [age] => 44
                )

        )

)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.