3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php /** * Task 2: Parse the string * * Parse the $input string and build object tree that represents this structure: * https://drive.google.com/file/d/0BwhWcFzxN6_mZ2hkQlhZTnRrMDA/view?usp=sharing * Use Node class to build the tree and dump it to output * * Realize Node::dump() function and use it to output the tree in format: * A * B * C * C * C * B * C * C * A * B * B * C */ $input = 'A(B(CCC)(BB)(CC))A(BB(C))'; class Node { public $letter; private $items = []; public function __construct($letter) { $this->letter = $letter; } public function addItem($item) { $this->items[] = $item; } public function dump($level = 0) { if($level != 0){ echo str_repeat(" ", $level). $this->letter. PHP_EOL; } foreach($this->items as $item){ $item->dump($level + 1); } } } function parseInput($node, $input){ $letter = $input[0]; $explInput = explode($letter, $input); foreach($explInput as $key=>$chunk){ if($key == 0){continue;} if(!empty($chunk)){ $chunk = preg_replace('/\((.*)\)/', '$1', $chunk); $chldNode = new Node($letter); $node->addItem($chldNode); parseInput($chldNode, $chunk); } else{ $node->addItem(new Node($letter)); } } } $root = new Node("R"); parseInput($root, $input); $root->dump();
based on FE5Tt
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0rc3
A B C C C ( B B ) C C A B B C