- str_repeat: documentation ( source)
- explode: documentation ( source)
- preg_replace: documentation ( source)
<?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();